How do I properly add a prefix (or suffix) to databinding in XAML?

c#, data-binding, wpf, xaml

Solution

If you've only got a single value you need to insert, you can use Binding's StringFormat property. Note that this requires .NET 3.5 SP1 (or .NET 3.0 SP2), so only use it if you can count on your production environment having the latest service pack.

<TextBlock Text="{Binding Name, Mode=OneWay, StringFormat='Hi, {0}'}"/>

If you wanted to insert two or more different bound values, I usually just make a StackPanel with Orientation="Horizontal" that contains multiple TextBlocks, for example:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="Good "/>
    <TextBlock Text="{Binding TimeOfDay}"/>
    <TextBlock Text=", "/>
    <TextBlock Text="{Binding Name}"/>
    <TextBlock Text="!"/>
</StackPanel>

Problem

How do I databind a single TextBlock to say "Hi, Jeremiah"? ``` <TextBlock Text="Hi, {Binding Name, Mode=OneWay}"/> ``` Looking for an elegant solution. What is out there? I'm trying to stay away from writing a converter for each prefix/suffix combination.

Original source

Related problems