How to set and change the culture in WPF

后端 未结 7 1645
孤独总比滥情好
孤独总比滥情好 2020-11-30 00:02

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:

7条回答
  •  悲哀的现实
    2020-11-30 00:05

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

提交回复
热议问题