开发者

Any built in way to format WPF bindings?

Scenario

I can't seem to find a way to format bindings in WPF using an IFormatProvider. Currently I've a property on my data source:

public int PersonNumber { get; set; }

This property is bound to a Label in XAML:

<Label Content="{Binding Path=PersonNumber}" />

As you can see it's a number, but should be formatted like 0000.00.000. Currently we use a separate IFormatProvider for such things in our old WinForms application.

Questions

  • Is formatting like this possible in WPF?
    • If yes, our preferred way is to still use an IFormatProvider, also possible?
    • If开发者_开发百科 no, what is a good alternative?

Thanks in advance!


You're looking for the ContentStringFormat property, which is on all ContentControl descendants including Label.

<Label Content="{Binding PersonNumber}" ContentStringFormat="000" />

I'm not sure whether WPF's formatting can make use of an IFormatProvider, though.


And to be complete, you could just add a String property to your ViewModel to get full control in C#:

public int PersonNumber { get; set; }
public string PersonNumberText { get { return ... } }


You can use the property StringFormat of Binding

Nice example: http://blogs.msdn.com/b/mikehillberg/archive/2008/05/29/trying-out-binding-stringformat.aspx


In addition to the posted answers, there's always available the converter way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜