Dienstag, 7. Januar 2014

Localization, ResourceManager, Dictionary, XAML Binding (VS12, .Net4.5)

Goal: easy implemetation of localization in the UI. Show a localized label... (VS/.Net, C#, WPF)

Requirement for all variants:

1) The base - were the words are .... in the VS Project "Properties" Section imagine a Resourcefile like "tx.resx" for english default keys&values and a Resourcefile "tx.de.resx" for the equivalent german keys&values. For instance there is a key called MyKeyToShowATranslatedValue. This key points to "Hello world" in the tx.resx and to "Hallo Welt" in the tx.de.resx.

Sample A:

2) In the View (XAML)...

Note: To use this variant, you need to doubleclick/open the Resourcefile tx.resx and tx.de.resx in VS. There, you see a combobox to change the "Access modifier". Change it to "public" and save each tx* file.

           Text="{x:Static propx:tx.MyKeyToShowATranslatedValue}"/>


Sample B:

2) add in "App.xaml.cs" and initialize the "tx" ResourceManager

public static ResourceManager tx = new ResourceManager("PROJECTNAMESPACE.Properties.tx", System.Reflection.Assembly.GetExecutingAssembly());

3) In the ViewModel-class...

3.1) create a Member to store the translated Words of tx.resx or tx.de.resx, whatever...

        private Dictionary<string, string> _words = new Dictionary<string,string>();
        public Dictionary<string, string> Words
            get { return _words; }
3.2) in the constructor of the ViewModel-class, copy the values of the ResourceManager in the Dictionary...

ResourceSet rs = App.tx.GetResourceSet(Thread.CurrentThread.CurrentUICulture, true, true);
            foreach (DictionaryEntry de in rs)
                _words.Add(de.Key.ToString(), de.Value.ToString());

4) In the XAML-View...

4.1) set the DataContext to the appropriate ViewModel

4.2) use the values of the Dictionary Keys in the VIEW using {Binding}....

Text="{Binding Path=Words[MyKeyToShowATranslatedValue]}" 

Benefit from the best Windows Desktop app in the world and use Strokey.Net!