4

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
  • Any answers for the related question? Commented Aug 13, 2009 at 15:44
  • I must have accidentally removed my comment on the related question when I re-wrote my answer. I just updated. Commented Aug 13, 2009 at 17:19

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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

Found a nice reference here with different examples : http://blog.stevex.net/string-formatting-in-csharp/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.