WPF 绑定 StringFormat 短日期字符串 [英] WPF Binding StringFormat Short Date String
问题描述
我想在 WPF 中使用短日期命名字符串格式.
I would like to use Short Date named string format in WPF.
我尝试了类似的东西:
<TextBlock Text="{Binding Date, StringFormat='Short Date'}" />
如何做到这一点?
推荐答案
试试这个:
<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />
这是文化敏感的,需要 .NET 3.5 SP1 或更高版本.
which is culture sensitive and requires .NET 3.5 SP1 or above.
注意:这是区分大小写的."d" 是 短日期格式说明符,而 "D"是长日期格式说明符.
NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.
MSDN 标准日期和时间页面上有完整的字符串格式列表格式字符串 以及对 这篇 MSDN 博客文章
但是,这有一个问题 - 它总是以美国格式输出日期,除非您自己将文化设置为正确的值.
However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.
如果不设置此属性,绑定引擎将使用绑定目标对象的语言属性.在 XAML 中,这默认为en-US"或从页面的根元素(或任何元素)继承值(如果已显式设置).
If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.
执行此操作的一种方法是在后面的代码中(假设您已将线程的区域性设置为正确的值):
One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):
this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
另一种方法是在绑定中设置转换器文化:
The other way is to set the converter culture in the binding:
<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />
虽然这不允许您本地化输出.
Though this doesn't allow you to localise the output.
这篇关于WPF 绑定 StringFormat 短日期字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!