Showing posts with label property. Show all posts
Showing posts with label property. Show all posts

Thursday, August 23, 2012

.NET XAML binding more than one property

When making views using XAML and with .NET you might sometimes want to combine more than one property into a textblock (e.g. for example showing the breadcrumbs of your location in a textblock). Something like the following for example:
Location1.Title + "." + Location2.Title + "." + Location3.Title

There are several ways of doing this.

One is creating a custom converter for MultiBinding that creates the string for you, pretty well explained here:
http://msdn.microsoft.com/en-us/library/system.windows.data.multibinding.converter.aspx
Which seems to be the common suggestion, but it involves writing a lot of code for just one field. And you might have to do this often!

Alternatively you can just combine a bunch of textblocks:
<textblock text="{Binding Path=Location1.Title}" />
<textblock text=", " />
<textblock text="{Binding Path=Location2.Title}" />
<textblock text=", " />
<textblock text="{Binding Path=Location3.Title}" />
Which is ok, but gets messy.

Or, you can (Since .NET 3.5 SP1) use MultiBinding property StringFormat:
<TextBlock Margin="5,0,0,0">
<TextBlock.Text>
<MultiBinding StringFormat="{}{0}, {1}, {2}">
<Binding Path="Location1.Title"/>
<Binding Path="Location2.Title"/>
<Binding Path="Location3.Title"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>

Note the empty bracket at the start of the StringFormat. When the XAML reader sees an opening bracket it reads this as the start of a markup extension (Binding). The empty bracket is an escape sequence to prevent the XAML reader from trying to interpret the {0} as a binding.
Note2: A space character will also work (" {0}, {1}, {2}").

Sources: http://stackoverflow.com/questions/505397/built-in-wpf-ivalueconverters, http://stackoverflow.com/questions/9001974/strange-multibinding-stringformat-issue, http://msdn.microsoft.com/en-us/library/ms744986.aspx