使用StringFormat的WPF格式标签

mHe*_*pMe 9 c# wpf

我有一个WPF应用程序.我有一些标签和一些数据网格绑定到一些公共属性.其中一些属性是数值.

在datagrids中,我一直在使用下面的行来确保这些值只显示两个小数位,这是有效的.但是,当我使用下面相同的行作为我的标签时,它似乎对显示没有影响,因为数字显示为大约9位小数.我不明白为什么它适用于datagrid但不适用于标签?

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"/>
Run Code Online (Sandbox Code Playgroud)

更新的代码

 <Label Grid.Row="3" Grid.Column="1"
        Content="{Binding Obs.Tstat}" ContentStringFormat="{}{0:0.#}}" 
        HorizontalAlignment="Center" Foreground="{StaticResource brushLinFont}" 
        FontSize="13" FontWeight="Bold"/>
Run Code Online (Sandbox Code Playgroud)

Roh*_*ats 24

对于label,您需要使用ContentStringFormat:

<Label Content="{Binding Obs.Tstat}" ContentStringFormat="{}{0:0.##}"/>
Run Code Online (Sandbox Code Playgroud)

原因:

Label的Content属性是类型object,StringFormat仅在绑定属性为type时使用String.

如果您使用TextBlock的Text属性尝试代码,它将正常工作,StringFormat因为Text属性是string类型.