Having hardcoded text with a binding in a TextBlock

Viewed 43935

In WPF, is there any way to have the Text property of a TextBlock to contain both hard coded text and a specific binding?

What I have in mind is something along the lines of the following (ofcourse, the below doesn't compile):

<TextBlock Text="Number of Fans: {Binding Artist.Fans.Count}"></TextBlock>
5 Answers

There is, if you are on .Net 3.5 SP1

<TextBlock Text="{Binding Path=Artist.Fans.Count, 
                 StringFormat='Number of Fans: {0}'}" />

Use Binding.StringFormat:

<TextBlock Text="{Binding Artist.Fans.Count, StringFormat='Number of Fans: {0}'}"/>

With XAML using Template 10 and MVVM:

Just to be clear:

  • By definition, binding binds values to properties of controls.
  • Under the MVVM paradigm as implemented in the 'Template 10' framework, the values are initialized in the ViewModel associated to the relevant XAML page.

Here is how to have hardcoded text together with a binding in a Text property:

    <Page
        ...
        xmlns:vm="using:doubleirish.ViewModels"
        xmlns:sys="using:System"
        xmlns:controls="using:Template10.Controls"
        ...

        <Page.DataContext>
            <vm:StocksViewModel x:Name="ViewModel" />
        </Page.DataContext>

        ...

        <controls:PageHeader ... Text="{x:Bind sys:String.Format('Ticker : {0}', ViewModel.Ticker)}">

    ...

    </Page>
Related