问题描述
所以我做了一个类似下面的示例应用程序。
Page.xamal
<StackLayout
VerticalOptions="CenterandExpand">
<Label Text="{x:Static local:AppResources.Title}" TextColor="Black"
HorizontalOptions="CenterandExpand" />
<Button Text="{x:Static local:AppResources.ClickMe}" Clicked="Button1_Clicked"/>
<Label Text="{x:Static local:AppResources.Title}" TextColor="Black"
HorizontalOptions="CenterandExpand" />
<Button Text="{x:Static local:AppResources.ClickMe}" Clicked="Button2_Clicked"/>
</StackLayout>
page.xamal.cs
private void Button1_Clicked(object sender,EventArgs e)
{
CultureInfo culture = new CultureInfo("th");
AppResources.Culture = culture;
}
随着xmarin表单文档的提供,我设置了AssemblyInfo.cs(公用文件夹)
[assembly: NeutralResourcesLanguage("en-GB")]
所以我的默认语言是“ en-GB”。
我有3个AppRerources.resx
- AppResources.resx
- AppResources.th.resx
- AppResources.en-GB.resx
但是当我按下第一个按钮时,我看不到该应用正在更改语言。
我在这里错过了什么?
解决方法
关于更改当前的Cultureinfo,建议您尝试使用 Plugin.Multilingual 来获取它。
首先,通过nuget软件包安装Plugin.Multilingual,如下定义.resx文件:
默认情况下,在TranslateExtension.cs文件的常量ResourceId中,它将假定您的资源文件已添加到项目的根目录中,并且resx文件名为AppResources。如果您将其添加到文件夹或使用其他名称命名为resx文件,则可以在其中进行更改。
public class TranslateExtension : IMarkupExtension
{
const string ResourceId = "MultilingualSample.AppResources";
static readonly Lazy<ResourceManager> resmgr = new Lazy<ResourceManager>(() => new ResourceManager(ResourceId,typeof(TranslateExtension).GetTypeInfo().Assembly));
public string Text { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Text == null)
return "";
var ci = CrossMultilingual.Current.CurrentCultureInfo;
var translation = resmgr.Value.GetString(Text,ci);
if (translation == null)
{
#if DEBUG
throw new ArgumentException(
String.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.",Text,ResourceId,ci.Name),"Text");
#else
translation = Text; // returns the key,which GETS DISPLAYED TO THE USER
#endif
}
return translation;
}
}
更多详细信息,请查看:
https://github.com/CrossGeeks/MultilingualPlugin
,在CultureInfo中传递您要设置的区域性参数,例如在我的示例中,将其设置为德语
CultureInfo ci = new CultureInfo("de-DE");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;