How to bind multiple values to a single WPF TextBlock?

Spen D picture Spen D · Mar 31, 2010 · Viewed 187.8k times · Source

I'm currently using the TextBlock below to bind the value of a property named Name:

<TextBlock Text="{Binding Name}" />

Now, I want to bind another property named ID to the same TextBlock.

Is it possible to bind two or more values to the same TextBlock? Can it be done with simple concatenation, like Name + ID and, if not, how else could this be approached?

Answer

Richard McGuire picture Richard McGuire · Mar 31, 2010

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.