Does StringFormat feature of WPF Xaml work on Labe

2019-01-15 05:26发布

问题:

I have bind my Amount Label's Content Property to a decimal property via DataContext. I am trying to apply stringformat but see no effect. Does StringFormat feature work on Label controls ?? Please tell me on which controls does this feature work. BTW following is the code for the Label Control for whom i want to apply the currency formatting

<Label Grid.Column="2" Content="{Binding Path=Amount, StringFormat={}{0:C}}" Height="23" HorizontalAlignment="Left" Margin="100,10,0,0" Name="tb" VerticalAlignment="Bottom" Width="120" />

回答1:

StringFormat works on properties of type string (when the object you are binding to is being converted to a string the string format is applied). The Content property is of type Object.

You can place a TextBlock inside your label to achieve the desired effect:

<Label Grid.Column="2" Height="23" HorizontalAlignment="Left" Margin="100,10,0,0" Name="tb" VerticalAlignment="Bottom" Width="120">
   <TextBlock Text="{Binding Path=Amount, StringFormat={}{0:C}}"/>
</Label>


回答2:

Try ContentStringFormat

http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/866f7934-8b10-4872-b306-122674fad5fa/

<Label Content=”{Binding Amount}” ContentStringFormat=”C” />