Search code examples
wpfmvvmbindingtextboxstring-formatting

String format in wpf


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?


Solution

  • 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