How to set Silverlight CurrentUICulture/CurrentCulture correctly?

一笑奈何 提交于 2019-11-29 10:25:35

Edit: Updated with the information that @Rumble found.

You need to do it like this to apply it to your UI objects as well.

First set the appropriate cultures when your application is loading up.

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-IN");
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-IN");

Next you need to set the XML Language property.

For Silverlight

var root = RootVisual as Page;
if (root != null)
{
    root.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
}

For WPF

FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(
            XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));

You can find an explanation for WPF here.

pawciu

Thanks to eandersson I came up with this extension for specific controls. I had a problem with my decimal input, parsing and validation. Somewhere in the way there was this InvariantCulture with '.' as separator instead of ','. It can be easily modifed to set up specific culture.

public class ElementCultureExtension
{
    public static bool GetForceCurrentCulture( DependencyObject obj )
    {
        return (bool)obj.GetValue( ForceCurrentCultureProperty );
    }

    public static void SetForceCurrentCulture( DependencyObject obj, bool value )
    {
        obj.SetValue( ForceCurrentCultureProperty, value );
    }

    public static readonly DependencyProperty ForceCurrentCultureProperty =
        DependencyProperty.RegisterAttached(
            "ForceCurrentCulture", typeof( bool ), typeof( ElementCultureExtension ), new PropertyMetadata( false, OnForceCurrentCulturePropertyChanged ) );

    private static void OnForceCurrentCulturePropertyChanged(
        DependencyObject d,
        DependencyPropertyChangedEventArgs e )
    {
        var control = (FrameworkElement)d;
        if( (bool)e.NewValue )
        {
            control.Language = XmlLanguage.GetLanguage( Thread.CurrentThread.CurrentCulture.Name );
        }
    }
}

In Xaml:

<TextBox Text="{Binding Path=DecimalValue, Mode=TwoWay}"
                         tools:ElementCultureExtension.ForceCurrentCulture="True" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!