Search code examples
wpflocalizationresourcesglobalizationcultureinfo

WPF use English culture resource even when UICulture is Arabic


I have been playing around WPF recently and I want to know how to use English culture resources even when the app culture is set to another culture say Arabic.

I have defined two resource files containing the HelloWorld key under a Resources folder.

  • AppResources.resx (Has HelloWorld = Hello World!)
  • AppResources.ar.resx (Has HelloWorld = مرحبا بالعالم)

HomePage.xaml

First I have declared the resource file's namespace as res

 xmlns:res="clr-namespace:Demo.Core.Resources;assembly=Demo.Core"

and then used it in the label to show Hello World!

<Label Content="{x:Static res:AppResources.HelloWorld}"/>

I have set Arabic as the app culture

CultureInfo cultureInfo = new CultureInfo("ar");
Resources.AppResources.Culture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;

I want to show the English Hello World! But it is showing the Arabic hello world (مرحبا بالعالم)

This is because I have set the CurrentUICulture & AppResources culture to Arabic. Is there any way with these setting, I could get still use the English strings defined in AppResources.resx file as it is in XAML? Basically, I want to ignore the culture setting and want to use the English resource directly in the XAML. Thanks in advance.


Solution

  • You could use the ResourceManager class to programmatically get a resource in a specified culture:

    ResourceManager rm = new ResourceManager(typeof(AppResources));
    lbl.Content = rm.GetString("HelloWorld", CultureInfo.InvariantCulture);
    

    You could use create a converter that performs the translation for you:

    public class ResourceConverter : IValueConverter
    {
        private static readonly ResourceManager s_rm = new ResourceManager(typeof(AppResources));
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string key = value as string;
            if (key != null)
                return s_rm.GetString(key, culture);
    
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    

    And use it in your XAML markup like this:

    <Label Content="{Binding Source=HelloWorld, 
        Converter={StaticResource ResourceConverter}, 
        ConverterCulture=en-US}" />