19

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.

Anvesh_96
  • 29
  • 7
Jeremiah
  • 5,386
  • 9
  • 38
  • 45

3 Answers3

43

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>
John Cummings
  • 1,949
  • 3
  • 22
  • 38
Joe White
  • 94,807
  • 60
  • 220
  • 330
  • 1
    Make sure you've got the 3.5SP1 installed to use this. – rmoore Jun 23 '09 at 19:31
  • @rmoore: Good catch. I've edited my answer to make that stand out. – Joe White Jun 23 '09 at 19:46
  • 4
    For multiple bindings, you could also use StringFormat in a MultiBinding. – rmoore Jun 23 '09 at 19:58
  • Holy crap... knowing about StringFormat earlier would have been amazing. – Will Eddins Jun 23 '09 at 20:09
  • @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 Jun 23 '09 at 20:24
  • @Joe White Yup, check out the remarks and examples here: http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.stringformat.aspx – rmoore Jun 23 '09 at 21:57
  • @rmoore Right there in the page I linked to... *smacks forehead* But wow. That is good to know! – Joe White Jun 24 '09 at 00:13
  • 2
    In case you've torn your hair out over and over again because you keep forgetting, THIS DOESN'T WORK ON ** ELEMENTS. Labels are a different animal, bindings don't work the same. See here for more: https://stackoverflow.com/questions/4206612/wpf-stringformat-on-label-content – Mageician Dec 17 '19 at 22:03
3

I think this should do it.

<TextBlock>
    <TextBlock Text="Hi, " />
    <TextBlock Text="{Binding Name, Mode=OneWay}" />
</TextBlock>
Gregory Higley
  • 15,923
  • 9
  • 67
  • 96
3

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 :)

Johnny
  • 41
  • 5