How to set and change the culture in WPF

2020-01-27 01:32发布

I have a .NET 4.0 WPF application where the user can change the language (culture) I simply let the user select a language, create a corresponding CultureInfo and set:

Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;

In the C# code this works fine. However in the WPF controls the culture is still en-US. This means for example that dates will be shown in the US format instead of whatever is correct for the current culture.

Apparently, this is not a bug. According to MSDN and several blog posts and articles on StackOverflow the WPF language does not automatically follow the current culture. It is en-US until you do this:

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

See for example StringFormat Localization issues in wpf.

I do not completely understand what is going on here. It seems the Language property on all frameworkelements is set to the current culture. Anyway, it works. I do this when the application starts up and now all controls works as expected, and e.g. dates is formatted according to the current culture.

But now the problem: According to MSDN FrameworkElement.LanguageProperty.OverrideMetadata can only be called once. And indeed, if I call it again (when the user changes the language) it will throw an exception. So I haven't really solved my problem.

The question: How can I reliably update the culture in WPF more than once and at any time in my applications life cycle?

(I found this when researching: http://www.nbdtech.com/Blog/archive/2009/03/18/getting-a-wpf-application-to-pick-up-the-correct-regional.aspx and it seems he has something working there. However, I can't imagine how to do this in my application. It seems I would have to update the language in all open windows and controls and refresh all existing bindings etc.)

7条回答
Animai°情兽
2楼-- · 2020-01-27 02:07

I'm not sure how to get around the "can't call OverrideMetadata multiple times" exception.

As a workaround, when the user changes UI cultures in your app, you could restart your app with that culture, passing in the new culture as a command line argument. Unless your users will be changing cultures often, this sounds like a reasonable solution.

查看更多
在下西门庆
3楼-- · 2020-01-27 02:09

Adaptive OverrideMetadata

Some form of reloading is inevitable, because changing a control's Language property doesn't make it update its text.

However, there's a way of overriding the metadata which allows you to set it once and have new controls automatically use the current culture:

FrameworkElement.LanguageProperty.OverrideMetadata(
    typeof(FrameworkElement),
    new FrameworkPropertyMetadata(
        System.Windows.Markup.XmlLanguage.Empty,
        default(PropertyChangedCallback),
        _CoerceCurrentXmlLang));

where the CoerceValueCallback is

private static object _CoerceCurrentXmlLang(DependencyObject d, object baseValue)
{
    var lang = baseValue as System.Windows.Markup.XmlLanguage;
    var culture = System.Globalization.CultureInfo.CurrentUICulture;
    return lang != null && lang.IetfLanguageTag.Equals(culture.Name, StringComparison.InvariantCultureIgnoreCase)
        ? lang
        : System.Windows.Markup.XmlLanguage.GetLanguage(culture.Name);
}

By itself this isn't quite enough, because newly created controls will get the default value System.Windows.Markup.XmlLanguage.Empty without it being coerced. However, if you then set xml:lang="" in your windows' XAML, that will be coerced, and then each new control will see that it inherits a value from its parent and will coerce it. The result is that new controls added to that window will use the current language.

PS As with many things in WPF, it would be quite a bit simpler if they hadn't been so keen to keep things internal. DefaultValueFactory would be a far more elegant way of doing this.

Reloading

The most extreme, but therefore reliable, way of reloading is just to create a new main window and discard the old one.

Almost as extreme but not quite is to arrange for the language setting to be changed only in a very simple pane of the main window with very little loaded, and that very little to be entirely databound to a viewmodel which supports forcing a property changed notification for everything.

Existing answers to this question have other suggestions.

查看更多
Lonely孤独者°
4楼-- · 2020-01-27 02:16

I'm going to chime in here.

I successfully did this using the OverrideMetadata() method that the OP mentioned:

var lang = System.Windows.Markup.XmlLanguage.GetLanguage(MyCultureInfo.IetfLanguageTag);
FrameworkElement.LanguageProperty.OverrideMetadata(
  typeof(FrameworkElement), 
  new FrameworkPropertyMetadata(lang)
);

But, I still found instances in my WPF in which the system culture was being applied for dates and number values. It turned out these were values in <Run> elements. It was happening because the System.Windows.Documents.Run class does not inherit from System.Windows.FrameworkElement, and so the overriding of metadata on FrameworkElement obviously had no effect.

System.Windows.Documents.Run inherits its Language property from System.Windows.FrameworkContentElement instead.

And so the obvious solution was to override the metadata on FrameworkContentElement in the same way. Alas, doing do threw an exception (PropertyMetadata is already registered for type System.Windows.FrameworkContentElement), and so I had to do it on the next descendant ancestor of Run instead, System.Windows.Documents.TextElement:

FrameworkContentElement.LanguageProperty.OverrideMetadata(
  typeof(System.Windows.Documents.TextElement), 
  new FrameworkPropertyMetadata(lang)
);

And that sorted out all my issues.

There are a few more sub-classes of FrameworkContentElement (listed here) which for completeness should have their metadata overridden as well.

查看更多
再贱就再见
5楼-- · 2020-01-27 02:19

I pretty much had the same issue.

I found this: http://www.codeproject.com/Articles/35159/WPF-Localization-Using-RESX-Files (might not be the original source).

It discusses a markup extension named "UICultureExtension" which is attached to the Language property of all framework elements that need localization (in XAML).

If you raise a UI language changed event, static extension managers in the background will update all registered framework elements.

查看更多
疯言疯语
6楼-- · 2020-01-27 02:23

I never found a way to do exactly what I asked for in the question. In my case I ended up solving it by having all my usercontrols inherit from a superclass that contained this:

/// <summary>
///   Contains shared logic for all XAML-based Views in the application. 
///   Views that extend this type will have localization built-in.
/// </summary>
public abstract class ViewUserControl : UserControl
{
    /// <summary>
    ///   Initializes a new instance of the ViewUserControl class.
    /// </summary>
    protected ViewUserControl()
    {
        // This is very important! We make sure that all views that inherit 
        // from this type will have localization built-in. 
        // Notice that the following line must run before InitializeComponent() on 
        // the view. Since the supertype's constructor is executed before the type's 
        // own constructor (which call InitializeComponent()) this is as it 
        // should be for classes extending this
        this.Language = XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag);
    }
}

When the user changes the language I then create new instances of any usercontrols that are currently running.

This solved my problem. However, I would still like a way to do this "automatically" (i.e. without having to keep track of any instantiated objects).

查看更多
▲ chillily
7楼-- · 2020-01-27 02:29

Just my two cents: After almost going crazy when trying to implement ComponentOne WPF controls (DataGrid and C1DatePicker) with my German language assembly I stumbled upon this page.

This seems to be directing in the right way: I just entered the above code into my App.xaml.cs / Application_startup routine and now German date/time formatting for C1DatePicker finally works.

Got to test DataGrid right after that.

    private void Application_Startup(object sender, StartupEventArgs e)
    {
        FrameworkElement.LanguageProperty.OverrideMetadata(
            typeof(FrameworkElement),
            new FrameworkPropertyMetadata(
            System.Windows.Markup.XmlLanguage.GetLanguage(CultureInfo.CurrentUICulture.IetfLanguageTag)));
    }

Thanks!

Update: Tested C1DataGrid for WPF - works! This solved all the problems I had with international Date / Time settings in my Applications. Great!

查看更多
登录 后发表回答