Search code examples
wpfdata-bindingbindingtextblockmultibinding

How to bind multiple values to a single WPF TextBlock?


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?


Solution

  • 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: This is only supported in .NET 3.5 SP1 and 3.0 SP2 or later.