2017-05-02 42 views
0

我试图让我的Xamarin Forms应用程序支持多种语言,如英语和阿拉伯语,这些语言基于不基于手机语言的用户选择。 以下代码显示如何将我的语言更改为阿拉伯语或英语。更改基于用户选择的应用程序语言配置

下面的代码是TranslateExtension从Xamarin Forms Samples部分:

public object ProvideValue(IServiceProvider serviceProvider) 
{ 
    if (Text == null) 
     return ""; 
    ResourceManager resmgr = new ResourceManager(ResourceId, typeof(TranslateExtension).GetTypeInfo().Assembly); 

    var translation = resmgr.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; // HACK: returns the key, which GETS DISPLAYED TO THE USER 
#endif 
    } 
    return translation; 
} 

谁能帮助我,告诉我如何使基于用户选择这项工作不是基于设备的语言。感谢帮助。

回答

0

显然你粘贴的代码来自this example。根据该示例,您可以看到有一个变量ci,其中包含扩展工作的CultureInfo。

因此,解决您的问题是正确设置ci变量。如果用户选择一个区域,你可能会保存在某个地方。在TranslateExtension构造函数中,您可以从保存它的位置检索该语言环境。

喜欢的东西:

public TranslateExtension() { 
    var userlocaleSvc = DependencyService.Get<IUserLocale>(); 
    if (userlocaleSvc.CustomCultureInfoSet()) // this method is made up 
    { 
     ci = userlocaleSvc.GetCultureInfo(); // this method is made up 
    } else { 
     ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo(); // fallback 
    } 
} 

您还可以设置对资源CultureInfo的,所以不使用TranslateExtension也得到适当的翻译资源(AppResources是你给你的资源文件的名称,就可以使用任何你想要的名称):

AppResources.Culture = new CultureInfo ("<shortcode of selected locale>"); 

参考Xamarin documentation on localization here

相关问题