【问题标题】:What's the XAML equivalent of .toFixed(2)?.toFixed(2) 的 XAML 等效项是什么?
【发布时间】:2012-12-08 17:47:35
【问题描述】:

我想在Label 中显示一个数字,它应该被格式化为 2 位小数(总是)。

示例:

<Label Content="{Binding MyMoneyAmount}" />

如果MyMoneyAmount = 100,那么它应该显示为:100.00 而不是 100

【问题讨论】:

    标签: wpf xaml binding string-formatting


    【解决方案1】:
    <Label Content="{Binding MyMoneyAmount, StringFormat={0:F2}}" />
    

    【讨论】:

    • 根据我的阅读和 Blend 4 中的快速测试,StringFormat 在这里不起作用,因为 Content 是 Object 类型 - 请参阅我的答案
    【解决方案2】:

    根据这个 SO Does StringFormat work on Label Content 以及我自己的测试,StringFormat 不适用于标签,因为 Content 是 Object 类型,这反映在此页面上的另一个答案中。

    您可以使用此解决方法(例如显示为货币):

    <Label><TextBlock Text="{Binding Source={myValue}, StringFormat={}{0:N2}}" /></Label>
    

    【讨论】:

    • 谢谢,这真的很有帮助。我一直在网上尝试各种例子,我没有意识到问题是Label
    • 很高兴为您提供帮助 - 请注意,使用 C2 代替 N2 也会引入您所在文化的货币符号
    • +1 @GrahamMc - 你是绝对正确的,我在回答中更关注 StringFormat 的使用。
    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2018-11-12
    相关资源
    最近更新 更多