Binding WPF Textblock to two properties using Multibinding

By | June 10, 2015

In the ancient and cruel world of WPF you might want to populate a TextBlock with a string which will contain data from different sources.

For example, you might want to display song and band in a single textBlock like, “Where Do You Go – No Mercy”.
The song name and band name can be two different fields in your class.  (BTW if you remember this song, then you are Awesome AND Old. Just like me.)

So this will work?

Text="{Binding Song - Band}"

No. You do databinding to a field. You can only perform one binding at a time.

Multibinding to rescue !!!!!

<TextBlock>
    <TextBlock.Text>   
        <MultiBinding StringFormat="{}{0} - {1}">
            <Binding Path="Song" />
            <Binding Path="Band" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

You can use this technique to bind two or more values to the same TextBlock.

The funny empty curly braces is there for a reason. They are required to escape the string. Otherwise the parser will complain about the curly braces in beginning of {0} – {1}.

Sadly this technique of binding TextBlock text to 2 different properties or more is not available in Silverlight.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.