WPF XAML 绑定和 CurrentCulture 显示 [英] WPF XAML Bindings and CurrentCulture Display
问题描述
当 CurrentCulture 更改时,我在 XAML 文档中看到一些无效行为.当我在窗口中有这样的元素时:
I'm seeing some invalid behavior from XAML documents when the CurrentCulture is changed. When I have some elements like this in a Window:
<Window x:Class="WpfLocalizationLocBaml.Test"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:glob="clr-namespace:System.Globalization;assembly=mscorlib"
x:Name="wndTest"
Title="Test" Height="300" Width="300">
<StackPanel>
<TextBlock x:Name="lblCultureName"
Text="{Binding Source={x:Static glob:CultureInfo.CurrentCulture},
Path=DisplayName}" />
<TextBlock x:Name="lblLocaleDateValue"
Text="{Binding ElementName=wndTest, Path=TestDate}"/>
<TextBlock x:Name="lblLocaleNumberValue"
Text="{Binding ElementName=wndTest,Path=NumberValue,StringFormat=c}" />
</StackPanel>
</Window>
以及 MessageBox.Show( NumberValue.ToString("c") );当表单开始时,我看到了不同的结果.
as well as a MessageBox.Show( NumberValue.ToString("c") ); when the form starts I'm seeing different results.
如果我使用默认语言运行表单,显然一切都很好.但是,如果我在代码中或在启动时更改区域性,则与日期和数字值的绑定仍会显示 en-US 格式.显示的 MessageBox.Show() 值恰当地反映了当前的文化.
If I run the form with the default language all is well obviously. However, if I change the culture in code or at startup the bindings to the date and number values still show en-US formatting. The MessageBox.Show() value displayed appropriately reflects the current culture.
问题:WPF 在绑定中不尊重 CurrentCulture 吗?如果是这样,究竟是什么决定了用于绑定的文化.就我而言,它显然是 en-US,但无论我在项目中将什么设置为默认语言,它总是绑定在 en-US 中.
Question: Does WPF not respect CurrentCulture in bindings? And if so what exactly determines the culture that is used for the bindings. It's clearly en-US in my case, but regardless what I set in my project as the default language it always binds in en-US.
任何想法表示赞赏...
Any ideas appreciated...
推荐答案
事实证明 WPF 在绑定中默认不尊重 CurrentCulture,而是默认为 XAML 文档中定义的 xml:Lang 设置或 en-US if不提供.这是相当蹩脚的行为——不知道为什么你不会像其他所有 UI 技术一样应用自动文化格式,但是......
It turns out that WPF does not respect the CurrentCulture by default in bindings, and instead defaults to xml:Lang setting defined in the XAML document or en-US if not provided. This is rather lame behavior - not sure why you would NOT have automatic culture formatting applied as every other UI technology, but...
幸运的是,有一个简单的解决方法可以应用于文档的构造函数或 Window/UserControl 基类:
Luckily there's an easy workaround that can be applied in the document's constructor or a Window/UserControl base class:
// MAKE SURE you set the language of the page explicitly or else
// all number and date formatting occurs using
this.Language = XmlLanguage.GetLanguage(
CultureInfo.CurrentCulture.IetfLanguageTag);
此博文中提供了更多信息:
There's more information available in this blog post:
http://www.west-wind.com/weblog/posts/796725.aspx
这篇关于WPF XAML 绑定和 CurrentCulture 显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!