views:

815

answers:

1

This should have a simple solution, but I can't seem to find it.

I want to do something like the following, where I have a data binding with a string format. The field is a text field, and I'd like to display it with a suffix (but not change the underlying data).

<Label Name="field" Content="{Binding obj.field, StringFormat=\{0\} suffix}" />

So I want obj.field's value, for instance "value", to display as "value suffix".

Is it really necessary to use a ValueConverter (or whatever) to do this? I'm thinking that if it's possible with the StringFormat construction, then there's some magic format option I just haven't encountered.

This leads to a related question: where can I find a reference for WPF StringFormat? I can find the reference for the c# String.Format formatting options, but these don't all seem to work in WPF (like what I've tried above).

+2  A: 

StringFormat will work if the target type is string. However, the type of Label's Content property is object. That is why the StringFormat has no effect. If you put a TextBlock inside the Label (or only use a TextBlock) and bind the Textblock's Text property, it should work fine.

<Label>
    <TextBlock Text="{Binding obj.field, StringFormat=\{0\} suffix}" />
</Label>

If you have other reasons to want to bind the value to the Label, you could also do the following.

<Label DataContext="{Binding obj.field}">
    <TextBlock Text="{Binding ., StringFormat=\{0\} suffix}" />
</Label>

Related question: I can't think of any reason why normal format strings that you can supply to string.Format() wouldn't work. They all should, both the standard and custom string. Here is a page with multiple examples. If there are any you find are not working, please provide examples.

Joel B Fant
Thanks. I've become aware that labels are not "lite" TextBlocks, as I imagined, but another animal entirely. Thanks for the reply.
Klay