使用“真实"WPF 绑定中的 CultureInfo.CurrentCulture,而不是来自 IetfLanguageTag 的 CultureInfo [英] Use "real" CultureInfo.CurrentCulture in WPF Binding, not CultureInfo from IetfLanguageTag

查看:20
本文介绍了使用“真实"WPF 绑定中的 CultureInfo.CurrentCulture,而不是来自 IetfLanguageTag 的 CultureInfo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就我而言:

我有一个 TextBlock 绑定到 DateTime 类型的属性.我希望它按照用户的区域设置显示.

I have a TextBlock Binding to a property of type DateTime. I want it to be displayed as the Regional settings of the User says.

<TextBlock Text="{Binding Date, StringFormat={}{0:d}}" />

我将语言属性设置为 WPF XAML 绑定和 CurrentCulture 显示说:

I am setting Language property as WPF XAML Bindings and CurrentCulture Display says:

this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);

但是这行代码只是将文本显示为 CultureInfo 的默认格式与 CurrentCulture 的 IetfLanguageTag 所说的不同,不像系统区域设置中选择的有效值所说:

But with this line of code it just displays the text as the default format of CultureInfo with IetfLanguageTag of CurrentCulture says, not as the effective value selected in systems region settings says:

(例如,对于de-DE",dd.MM.yyyy 用于代替选定的 yyyy-MM-dd)

(e.g. for "de-DE" dd.MM.yyyy is used instead of selected yyyy-MM-dd)

有没有一种方法 Binding 可以使用正确的格式,而无需在每个 Binding 上定义 ConverterCulture?

Is there a way Binding uses the correct format without defining ConverterCulture on every single Binding?

代码中

string.Format("{0:d}",Date);

使用正确的文化设置.

另一种无法正常工作的方式(就像这样.Language = ... 确实如此):

another way which doesn't work as desired (like this.Language = ... does):

xmlns:glob="clr-namespace:System.Globalization;assembly=mscorlib"

<Binding Source="{x:Static glob:CultureInfo.CurrentCulture}" 
 Path="IetfLanguageTag" 
 ConverterCulture="{x:Static glob:CultureInfo.InvariantCulture}" />

推荐答案

您可以创建绑定的子类(例如 CultureAwareBinding),它会在创建时自动将 ConverterCulture 设置为当前文化.

You can create a subclass of binding (e.g. CultureAwareBinding) which sets the ConverterCulture automatically to the current culture when created.

这不是一个完美的解决方案,但它可能是唯一的解决方案,因为追溯性地强制绑定尊重文化可能会破坏 WPF 中依赖于这种行为的其他代码.

It's not a perfect solution, but it's probably the only one, since retroactively forcing Binding to respect the culture could break other code in WPF which depends on this behavior.

如果您需要更多帮助,请告诉我!

Let me know if you need more help!

这篇关于使用“真实"WPF 绑定中的 CultureInfo.CurrentCulture,而不是来自 IetfLanguageTag 的 CultureInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆