How to bind multiple values to a single WPF TextBlock? How to bind multiple values to a single WPF TextBlock? wpf wpf

How to bind multiple values to a single WPF TextBlock?


You can use a MultiBinding combined with the StringFormat property. Usage would resemble the following:

<TextBlock>    <TextBlock.Text>            <MultiBinding StringFormat="{}{0} + {1}">            <Binding Path="Name" />            <Binding Path="ID" />        </MultiBinding>    </TextBlock.Text></TextBlock>

Giving Name a value of Foo and ID a value of 1, your output in the TextBlock would then be Foo + 1.

Note: that this is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.


I know this is a way late, but I thought I'd add yet another way of doing this.

You can take advantage of the fact that the Text property can be set using "Runs", so you can set up multiple bindings using a Run for each one. This is useful if you don't have access to MultiBinding (which I didn't find when developing for Windows Phone)

<TextBlock>  <Run Text="Name = "/>  <Run Text="{Binding Name}"/>  <Run Text=", Id ="/>  <Run Text="{Binding Id}"/></TextBlock>


If these are just going to be textblocks (and thus one way binding), and you just want to concatenate values, just bind two textblocks and put them in a horizontal stackpanel.

    <StackPanel Orientation="Horizontal">        <TextBlock Text="{Binding Name}"/>        <TextBlock Text="{Binding ID}"/>    </StackPanel>

That will display the text (which is all Textblocks do) without having to do any more coding. You might put a small margin on them to make them look right though.