我最近一直在WPF周围玩游戏,即使将应用程序文化设置为另一种文化,我也想知道如何使用英语文化资源。
我已经在资源文件夹下定义了包含Helloworld键的两个资源文件。
- 批准resx (有Helloworld = Hello world!)
- 批准ar.resx (有helloworld=急
homepage.xaml
首先,我将资源文件的命名空间声明为res
xmlns:res="clr-namespace:Demo.Core.Resources;assembly=Demo.Core"
然后在标签中使用它显示 Hello World!
<Label Content="{x:Static res:AppResources.HelloWorld}"/>
我将阿拉伯语设置为App Culture
CultureInfo cultureInfo = new CultureInfo("ar");
Resources.AppResources.Culture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
我想展示英语Hello World!但它显示了阿拉伯人的Hello World(&strong>
)这是因为我已经设置了当前的文化&amp;批准文化为阿拉伯语。这些设置有什么办法,我仍然可以使用onserveSources.resx文件中定义的英语字符串,就像在XAML中一样?基本上,我想忽略文化环境,并希望直接在XAML中使用英语资源。预先感谢。
您可以使用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}" />
此线程C#:如何从某种文化中获取资源字符串似乎可以回答您想要的内容。基本上它归结为打电话 Resources.ResourceManager.GetString("foo", new CultureInfo("en-US"));
如果您需要直接从XAML使用它,请写下标记文字,给定资源密钥,返回所需的本地化字符串
[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
}
}
我更喜欢这个appaach,因为它更加合成。XAML:
<Label Content={EnglishLoc key}/>