如何正确设置Silverlight的CurrentUICulture/CurrentCulture?

7

我正在使用C#开发SL5应用程序,希望对其进行国际化。我找到了以下内容来设置UI区域设置:

var culture = new CultureInfo(Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName);
Thread.CurrentThread.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;

一些控件,例如DatePicker似乎能够识别此设置。然而,如果我使用“d”格式字符串格式化任何日期时间,仍会得到默认格式“M/dd/yyyy”。
Silverlight如何解释区域性,如何为整个应用程序正确设置它呢?
谢谢。
更新:
找到答案:
首先,在Application_Startup中设置适当的区域性:
var culture = new CultureInfo("nl-BE");
Thread.CurrentThread.CurrentUICulture = culture;
Thread.CurrentThread.CurrentCulture = culture;

关键要素是添加以下内容以强制RootVisual的文化/语言:
var root = RootVisual as Page;
if (root != null)
{
    root.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);
}
2个回答

11

编辑:已更新包含@Rumble找到的信息。

你需要这样做来将其应用于你的UI对象。

首先,在你的应用程序加载时设置适当的文化。

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

接下来您需要设置XML语言属性。

对于Silverlight:

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

对于WPF

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

您可以在这里找到有关WPF的解释


首先,感谢您的快速回复。在SL5中似乎没有OverrideMetadata方法。CurrentCulture也不包含IetfLanguageTag属性... - rumblefx0
1
看起来你已经解决了。我更新了我的答案,加入了你找到的信息。 - eandersson

1
感谢eandersson,我为特定控件设计了这个扩展。我的小数输入、解析和验证出了问题,其中一个地方使用的是InvariantCulture,小数点分隔符是'.'而不是','。可以轻松地修改以设置特定文化。
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 );
        }
    }
}

在Xaml中:
<TextBox Text="{Binding Path=DecimalValue, Mode=TwoWay}"
                         tools:ElementCultureExtension.ForceCurrentCulture="True" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接