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

问题描述 投票:1回答:2

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

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

  • AppResources.resx(HelloWorld = Hello World!)
  • AppResources.ar.resx(HelloWorld = Hello World)

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中使用英语资源。提前致谢。

wpf localization resources globalization cultureinfo
2个回答
2
投票

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

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}" />

2
投票

这个帖子C#: How to get a resource string from a certain culture似乎给出了你正在寻找的答案。基本上它归结为调用Resources.ResourceManager.GetString("foo", new CultureInfo("en-US"));如果你需要直接从XAML使用它然后编写MarkupExtension,给定资源键,返回所需的本地化字符串

[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}/>
© www.soinside.com 2019 - 2024. All rights reserved.