Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 400
Jeremiah Avatar asked Jun 23 '09 19:06

Jeremiah


3 Answers

correction(minor) to @Joe White's solution

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

single quotes are required to apply stringformat successfully
worked for me :)

like image 42
Johnny Avatar answered Nov 11 '22 15:11

Johnny


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>
like image 128
Joe White Avatar answered Nov 11 '22 17:11

Joe White


I think this should do it.

<TextBlock>
    <TextBlock Text="Hi, " />
    <TextBlock Text="{Binding Name, Mode=OneWay}" />
</TextBlock>
like image 3
Gregory Higley Avatar answered Nov 11 '22 16:11

Gregory Higley