XAML中的StringFormat [英] StringFormat in XAML
问题描述
我正在尝试格式化我的字符串
,每3位都有一个逗号,如果它不是一个整数,我就是十进制格式。我已经检查了大约20个例子,这是我最近来的:
I am trying to format my string
to have commas every 3 places, and a decimal if it is not a whole number. I have checked roughly 20 examples, and this is the closest I have come:
<TextBlock x:Name="countTextBlock" Text="{Binding Count, StringFormat={0:n}}" />
但是我得到一个在类型''中找不到属性StringFormat绑定'。
错误。
任何想法这里有什么问题? Windows Phone 8.1似乎与WPF有所不同,因为所有WPF资源都说这是完成的。
Any ideas what is wrong here? Windows Phone 8.1 appears to differ from WPF, because all of the WPF resources say that this is how it is done.
( string
不断更新,所以我需要在
XAML
中的代码,我还需要保持绑定,除非我不能让我的蛋糕和
(The string
is updated constantly, so I need the code to be in the XAML
. I also need it to remain binded. Unless of course I cannot have my cake and eat it too.)
推荐答案
似乎,类似于绑定
在WinRT中,Windows Phone Universal Apps中的绑定
不具有 StringFormat
属性。解决这个限制的一种可能办法是使用 Converter
,如这个博文,
It seems that, similar to Binding
in WinRT, Binding
in Windows Phone Universal Apps doesn't have StringFormat
property. One possible way to work around this limitation is using Converter
as explained in this blog post,
为了总结这个帖子,你可以创建一个 IValueConverter
接受字符串格式的参数:
To summarize the post, you can create an IValueConverter
implmentation that accept string format as parameter :
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中创建上述转换器的资源,然后你可以这样使用,例如:
Create a resource of above converter in your XAML, then you can use it like this for example :
<TextBlock x:Name="countTextBlock"
Text="{Binding Count,
Converter={StaticResource StringFormatConverter},
ConverterParameter='{}{0:n}'}" />
这篇关于XAML中的StringFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!