Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF XAML Bindings and CurrentCulture Display

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>

as well as a MessageBox.Show( NumberValue.ToString("c") ); when the form starts I'm seeing different results.

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.

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...

like image 348
Rick Strahl Avatar asked Nov 30 '22 12:11

Rick Strahl


2 Answers

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...

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

like image 133
Rick Strahl Avatar answered Dec 08 '22 01:12

Rick Strahl


It's also worth pointing out that the same thing happens in Silverlight, with the same solution except for swapping IetfLanguageTag for Name.

like image 40
Bernard Avatar answered Dec 07 '22 23:12

Bernard