views:

238

answers:

2

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.

+11  A: 

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, e.g.:

<StackPanel Orientation="Horizontal">
    <TextBlock Text="Good "/>
    <TextBlock Text="{Binding TimeOfDay}"/>
    <TextBlock Text=", "/>
    <TextBlock Text="{Binding Name}"/>
    <TextBlock Text="!"/>
</StackPanel>
Joe White
Make sure you've got the 3.5SP1 installed to use this.
rmoore
Thank you! It worked superbly!
Jeremiah
@rmoore: Good catch. I've edited my answer to make that stand out.
Joe White
For multiple bindings, you could also use StringFormat in a MultiBinding. <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{1},{0}"> <Binding Path="Prop1" /> <Binding Path="Prop2" /> </MultiBinding> </TextBlock.Text> </TextBlock>
rmoore
Holy crap... knowing about StringFormat earlier would have been amazing.
Will Eddins
@rmoore: I haven't worked with MultiBinding to speak of, but I had the impression that it always required you to write your own MultiValueConverter -- that there weren't any useful MultiValueConverters that shipped with the framework. Can StringFormat replace that?
Joe White
@Joe White Yup, check out the remarks and examples here: http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.stringformat.aspx
rmoore
@rmoore Right there in the page I linked to... *smacks forehead* But wow. That is good to know!
Joe White
A: 

I think this should do it.

<TextBlock>
    <TextBlock Text="Hi, " />
    <TextBlock Text="{Binding Name, Mode=OneWay}" />
</TextBlock>
Gregory Higley
Joe White's StringFormat solution is probably the way to go. I'd forgotten about that.
Gregory Higley