加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

XAML中的StringFormat

发布时间:2020-12-14 01:48:43 所属栏目:Windows 来源:网络整理
导读:我试图将我的字符串格式化为每3个位置使用逗号,如果不是整数,则使用小数.我检查了大约20个例子,这是我最接近的例子: TextBlock x:Name="countTextBlock" Text="{Binding Count,StringFormat={0:n}}" / 但我得到一个属性’StringFormat’在类型’绑定’中找
我试图将我的字符串格式化为每3个位置使用逗号,如果不是整数,则使用小数.我检查了大约20个例子,这是我最接近的例子:
<TextBlock x:Name="countTextBlock" Text="{Binding Count,StringFormat={0:n}}" />

但我得到一个属性’StringFormat’在类型’绑定’中找不到.错误.

任何想法在这里有什么不对? Windows Phone 8.1似乎与WPF不同,因为所有WPF资源都说这就是它的工作方式.

(字符串不断更新,所以我需要代码在XAML中.我还需要它保持绑定.除非我当然不能吃蛋糕而且也吃掉它.)

看起来,类似于WinRT中的Binding,Windows Phone Universal Apps中的绑定没有StringFormat属性.解决此限制的一种可能方法是使用Converter,如 this blog post中所述,

要总结帖子,您可以创建一个接受字符串格式作为参数的IValueConverter implmentation:

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,string language)
    {
        throw new NotImplementedException();
    }
}

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读