MVVM conform localization in WPF Applications

末鹿安然 提交于 2020-01-12 03:17:38

问题


How can I localize an WPF Application using the MVVM Pattern? I really want to do it the "right" way.

My current approach is that I use .resx Resource files to localize my application.

I included them in my xaml code

xmlns:localization="clr-namespace:ClientLibTestTool.ViewLanguages"

and access them like this:

        <Button x:Name="BtnGenerate" 
                Content="{x:Static localization:localization.ButtonGenerate}"/>

My Questions:

  1. Is there a better way to do it?
  2. How can i test the different languages (load application with different language settings)?
  3. Is it possible to change the language at runtime?

Answers:

Question 1:

Question 2: (Thank you, stijn)

public MainWindow()
{
    // Debug Settings
    localization.Culture = CultureInfo.GetCultureInfo("en-US");
    // localization.Culture = CultureInfo.GetCultureInfo("de-DE");
    this.InitializeComponent();
}

Question 3: (Thank you, stijn)

Not really, it is necessary to redraw the complete window.


回答1:


This is the appropriate way to do it, as far as I'm concerned. To switch languages, change the culture used by the localization class:

localization.Culture = CultureInfo.GetCultureInfo( "de-DE" );

Since all strings are fetched at runtime (all calls in the generated Designer.cs files look like ResourceManager.GetString( "SomeString", resourceCulture ); and resourceCulture is what gets set by the call above, this affects what you get at runtime. However supose you use the values in menu items etc from within xaml, you have to rebuild the entire menu before this takes effect.



来源:https://stackoverflow.com/questions/15268699/mvvm-conform-localization-in-wpf-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!