我有一个 WPF 应用程序。我有一些标签和一些数据网格绑定(bind)到一些公共(public)属性。其中一些属性是数值。
在数据网格中,我一直使用下面的行来确保值只显示两位小数,这是有效的。然而,当我在下面使用同一行作为我的标签时,它似乎对显示没有影响,因为数字显示到大约 9 位小数。我不明白为什么它适用于数据网格而不适用于标签?
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"/>
更新代码
<Label Grid.Row="3" Grid.Column="1"
Content="{Binding Obs.Tstat}" ContentStringFormat="{}{0:0.#}}"
HorizontalAlignment="Center" Foreground="{StaticResource brushLinFont}"
FontSize="13" FontWeight="Bold"/>
最佳答案
对于标签,您需要使用 ContentStringFormat :
<Label Content="{Binding Obs.Tstat}" ContentStringFormat="{}{0:0.##}"/>
原因:
Label 的 Content
属性是 object
类型,StringFormat
仅在绑定(bind)属性是 String
类型时使用.
如果您使用 TextBlock 的 Text
属性尝试您的代码,它将在 StringFormat
中正常工作,因为 Text 属性是字符串类型。
关于c# - 使用 StringFormat 的 WPF 格式化标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22594958/