WPF:String的StringFormat问题

Jon*_*len 22 wpf binding

这些版本按预期工作:

<DataGridTextColumn Header="Total Units" Binding="{Binding TotalUnits, Mode=OneWay, StringFormat=N0}"/>

<TextBlock Text="{Binding TotalUnits, Mode=OneWay, StringFormat=N0}"/>
Run Code Online (Sandbox Code Playgroud)

当我用标签尝试它时,StringFormat是iqnored,我得到"123.000000"而不是"123".

<Label Content="{Binding TotalUnits, Mode=OneWay, StringFormat=N0}"/>
Run Code Online (Sandbox Code Playgroud)

TotalUnits是十进制.

发生什么了?

Bry*_*son 47

任何具有Content属性的东西ContentStringFormat都必须使用特殊属性,而不是在Binding中指定StringFormat.

像这样:

<Window.Resources xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <sys:Int16 x:Key="MyValue">100</sys:Int16>
</Window.Resources>

<StackPanel DataContext="{StaticResource MyValue}">

    <!-- using Label -->
    <Label Content="{Binding}" ContentStringFormat="{}{0:C}" />

    <!-- using TextBlock-->
    <TextBlock Text="{Binding, StringFormat={0:C}}" />

</StackPanel>
Run Code Online (Sandbox Code Playgroud)