String format in wpf

。_饼干妹妹 提交于 2019-12-11 05:32:28

问题


I have a TextBox on WPF that is related to the float variable in my model

Following the TextxBox:

 <TextBox Text="{Binding Position, StringFormat=f4}"/>

I want that TextBox will display a maximum 4 numbers after the point.

So I put StringFormat=f4.

But now, even when I have less than 4 numbers after the point and when I have a whole number it displays with 4 digits after the point.

For example, the number 0 is shows that: 0.0000

I want as long as it did not pass the four numbers, display it in a normal way, how can I do this?


回答1:


you could try with StringFormat="{}{0:0.####}"

This syntax with {} is due to the fact that we set a WPF property equal to a string that contains curly bracket symbols. Curly bracket symbols are interpreted by WPF in a particular way and would not be interpreted as part of the string. Without the {} the code would not compile. {} allows you to set a WPF to a string value that contains curly bracket symbols.

You can have for example a look at the link String formatting in WPF and Silverlight




回答2:


Take a look at this link about Custom Numeric Format Strings. I think this is what you might be looking for.

Or alternatively, try this;

<TextBox Text="{Binding Position, StringFormat='{}{0:#,0000}'}"/>

Hope this helps! :)

EDIT:

This previous question might help also;

WPF binding StringFormat syntax



来源:https://stackoverflow.com/questions/16439402/string-format-in-wpf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!