Search code examples
c#wpflocalization

WPF Localization Multiple languages ResourceDictionary vs Resource File (.RESX)


I am trying to set a WPF for multi languages.

I have gone the ResourceDictionary as found on other posts, but just to recap:

1 - Create ResourceDictionary files: \Resources\StringResources.xaml for default (en) and \Resources\FR\StringResources.xaml for french (fr)

2 - Call the method below on app start, I placed it in my app.xaml.cs

    private void SetLanguageDictionary()
        {
            ResourceDictionary dict = new ResourceDictionary();
            switch (Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName)
            {
                case "en":
                    dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);
                    break;

                case "fr":
                    dict.Source = new Uri("..\\Resources\\FR\\StringResources.xaml", UriKind.Relative);
                    break;

                default:
                    dict.Source = new Uri("..\\Resources\\StringResources.xaml", UriKind.Relative);
                    break;
            }
            this.Resources.MergedDictionaries.Add(dict);
        }

3 - Call it from your xaml files, e.g.:

<button Text="{DynamicResource settings}" />

4 - in ResourceDictionary file:

xmlns:system="clr-namespace:System;assembly=mscorlib"

<system:String x:Key="settings">Settings</system:String>

That is super easy, however first problem is: How do you set it in the code behind? I was looking at other posts and they seem to mention things like: (However does not work for me..)

string str = Resources.ResourceManager.GetString(settings); 

Is there anything special?




Now going further, while this works very well, what about using .resx files? They seem quite a lot easier to manage and can even auto translate.. But is that a preferred way to go?

Would they also use 1 file per language? Where would we set the file to choose on app start? I seem to be struggling finding any help on this unfortunately...


Solution

  • TryFindResource is how finding a resource dynamically works from code:

    object resource = Application.Current.TryFindResource("settings");
    string settingsString = resource as string;
    if(settingsString!=null)
    {
       // Use it
    }
    

    For StaticResources you can just use:

    string settingsString = Application.Current.Resources["settings"] as string;