【问题标题】:StringFormat in XAMLXAML 中的字符串格式
【发布时间】:2014-07-26 00:44:26
【问题描述】:

我正在尝试将我的string 格式化为每 3 位逗号,如果不是整数则为小数。我检查了大约 20 个示例,这是我最接近的示例:

<TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" />

但我收到 The property 'StringFormat' was not found in type 'Binding'. 错误。

有什么想法吗? Windows Phone 8.1 似乎与 WPF 不同,因为所有 WPF 资源都表明它是这样完成的。

string 不断更新,所以我需要将代码放在XAML 中。我还需要它保持绑定状态。除非我当然不能吃蛋糕。)

【问题讨论】:

标签: xaml data-binding string-formatting windows-phone-8.1


【解决方案1】:

看起来,与 WinRT 中的 Binding 类似,Windows Phone 通用应用程序中的 Binding 似乎没有 StringFormat 属性。解决此限制的一种可能方法是使用Converter,如this blog post 中所述,

总结这篇文章,您可以创建一个接受字符串格式作为参数的IValueConverter 实现:

public sealed class StringFormatConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value == null)
            return null;

        if (parameter == null)
            return value;

        return string.Format((string)parameter, value);
    }

    public object ConvertBack(object value, Type targetType, object parameter,
        string language)
    {
        throw new NotImplementedException();
    }
}

在您的 XAML 中创建上述转换器的资源,然后您可以像这样使用它,例如:

<TextBlock x:Name="countTextBlock" 
           Text="{Binding Count, 
                          Converter={StaticResource StringFormatConverter},
                          ConverterParameter='{}{0:n}'}" />

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2013-09-09
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多