XAML中的字符串格式
我正在尝试格式化我的XAML中的字符串格式,xaml,data-binding,string-formatting,windows-phone-8.1,Xaml,Data Binding,String Formatting,Windows Phone 8.1,我正在尝试格式化我的字符串,使其每3位有逗号,如果不是整数,则为十进制。我已经检查了大约20个例子,这是我最近的一个: <TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" /> 但是我得到一个在类型“Binding”中找不到属性“StringFormat”。错误 你知道这里怎么了吗?WindowsPhone8.1似乎不同于WPF,因为所有WPF资源都说这就是它的实现方式 (字
字符串
,使其每3位有逗号,如果不是整数,则为十进制。我已经检查了大约20个例子,这是我最近的一个:
<TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" />
但是我得到一个在类型“Binding”中找不到属性“StringFormat”。
错误
你知道这里怎么了吗?WindowsPhone8.1似乎不同于WPF,因为所有WPF资源都说这就是它的实现方式
(字符串不断更新,因此我需要将代码放在
XAML中。我还需要它保持绑定状态。当然,除非我不能既吃蛋糕又吃蛋糕。)看起来,与WinRT中的绑定
类似,Windows Phone通用应用程序中的绑定
没有StringFormat
属性。解决此限制的一种可能方法是使用转换器
,如中所述
要总结文章,您可以创建一个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}'}" />