Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF formatting labels with StringFormat

Tags:

c#

wpf

I have a WPF application. I have some labels and some datagrids which are bound to some public properties. Some of these properties are numerical values.

In the datagrids I have been using the line below to ensure the values only display two decimal places, which works. However when I use the same line below for my label it appears to have no effect on the display as the number shows to about 9 decimal places. I don't understand why it works for the datagrid but not the label?

StringFormat={}{0:0.##}



<Label Grid.Row="3" Grid.Column="1"
       Content="{Binding Obs.Tstat, StringFormat={}{0:0.#}}" 
       HorizontalAlignment="Center" Foreground="{StaticResource brushLinFont}" 
       FontSize="13" FontWeight="Bold"/>

Updated code

 <Label Grid.Row="3" Grid.Column="1"
        Content="{Binding Obs.Tstat}" ContentStringFormat="{}{0:0.#}}" 
        HorizontalAlignment="Center" Foreground="{StaticResource brushLinFont}" 
        FontSize="13" FontWeight="Bold"/>
like image 737
mHelpMe Avatar asked Mar 23 '14 18:03

mHelpMe


2 Answers

For label you need to use ContentStringFormat:

<Label Content="{Binding Obs.Tstat}" ContentStringFormat="{}{0:0.##}"/>

Reason:

Label's Content property is of type object and StringFormat is used only when binding property is of type String.

If you try your code with TextBlock's Text property it will work fine with StringFormat because Text property is of type string.

like image 71
Rohit Vats Avatar answered Oct 21 '22 18:10

Rohit Vats


Just a quick addition I'd like to post along these lines in case anyone else runs in to it... My application uses localization since it has multi-country support, but we also support user's system settings. We noticed ContentStringFormat defaults to your UI culture.

That caused an issue in one of our forms where the user's machine-specific decimal places they had configured in windows settings were not respected when you specified the ContentStringFormat.

Since the ContentPresenter simply takes the string format without the converter culture you could normally specify in the binding , this means that a format of say: 0:N will only return two decimal places if English is my current UI culture, even though I have 5 decimals specified on my windows settings.

In our case we applied some binding overrides to work around this, but mainly just wanted to add this extra bit of info in case anyone else runs in to it ;)

like image 35
K.DW Avatar answered Oct 21 '22 19:10

K.DW