即使 UICulture 是阿拉伯语,WPF 也使用英语文化资源

WPF use English culture resource even when UICulture is Arabic

我最近一直在玩 WPF,我想知道如何使用英语文化资源,即使应用程序文化设置为另一种文化,比如阿拉伯语。

我在 Resources 文件夹下定义了两个包含 HelloWorld 密钥的资源文件。

HomePage.xaml

首先我将资源文件的命名空间声明为 res

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

然后在标签中使用它来显示 Hello World!

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

我已将阿拉伯语设置为应用文化

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

我要显示英文的Hello World!但它显示的是阿拉伯语 hello world (مرحبا بالعالم)

这是因为我已将 CurrentUICulture & AppResources 文化设置为阿拉伯语。这些设置有什么办法,我仍然可以使用 AppResources.resx 文件中定义的英文字符串,就像在 XAML 中一样?基本上,我想忽略文化设置,想直接在XAML中使用英文资源。提前致谢。

您可以使用 ResourceManager class 以编程方式获取指定区域性的资源:

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

您可以使用创建一个转换器来为您执行翻译:

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();
    }
}

并像这样在 XAML 标记中使用它:

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

此讨论帖 C#: How to get a resource string from a certain culture 似乎可以为您提供所需的答案。基本上可以归结为打电话 Resources.ResourceManager.GetString("foo", new CultureInfo("en-US")); 如果您需要直接从 XAML 使用它,那么编写 MarkupExtension,给定资源键,returns 需要本地化字符串

[MarkupExtensionReturnType(typeof(string))]
public class EnglishLocExtension : MarkupExtension 
{
  public string Key {get; set;}
  public EnglishLocExtension(string key)
  { 
     Key = key; 
  }
  public override object ProvideValue(IServiceProvider provider) 
  { // your lookup to resources 
  }
}

我更喜欢这种方法,因为它更简洁。 Xaml:

<Label Content={EnglishLoc key}/>