我需要创建一个支持多语言的应用程序。
所以我做了一个如下所示的示例应用程序。
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(公共(public)文件夹)
[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;
}
}
更详细的信息,请查看:
关于c# - 如何以 xamarin 形式动态更改 CultureInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64458156/