[英]How Change the CultureInfo Dynamically in xamarin forms
我需要創建一個支持多語言的應用程序。
所以我做了一個像下面這樣的示例應用程序。
頁面.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>
頁面.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
但是當我按下第一個按鈕時,我看不到該應用程序正在更改語言。
我在這里錯過了什么?
關於更改當前的cultureinfo,我建議你可以嘗試使用Plugin.Multilingual來獲取。
首先,通過nuget包安裝Plugin.Multilingual,定義.resx文件如下:
默認情況下,在常量 ResourceId 中的 TranslateExtension.cs 文件中,它會假設您的資源文件已添加到項目的根目錄中,並且 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;
}
}
更詳細的信息,請看:
在 CultureInfo 中傳遞參數你想設置的文化,例如我在我的例子中將它設置為德語
CultureInfo ci = new CultureInfo("de-DE");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.