新的语言Xamarin后刷新UI

时间:2019-05-14 13:19:24

标签: user-interface xamarin.forms refresh translation

Re-evaluate all values in xaml page calculated by a markup-extension

我尝试实现此解决方案,但是我有一个ObservableCollection,其中包含要绑定到我的MasterDetails页面的listview中的Title,并且它不起作用。我真的不知道如何实现此功能,但是只有一个标签成功完成了。如果有人可以帮助我。谢谢

我的物品清单:

public ObservableCollection<MainMenuViewItem> MenuItems {
            get {
                return new ObservableCollection<MainMenuViewItem>(new[]
                {
                    new MainMenuViewItem { Id = 0, Title = Translator.TranslatorInstance["lblHome"], TargetType=typeof(HybridWebView),ViewModelType=HybridViewTypeEnum.Home },
                    new MainMenuViewItem { Id = 1, Title = Translator.TranslatorInstance["lblListOfDeliverySlip"], TargetType=typeof(HybridWebView),ViewModelType=HybridViewTypeEnum.ListDeliverySlip },
                    new MainMenuViewItem { Id = 2, Title = Translator.TranslatorInstance["lblSettings"], TargetType=typeof(ParametersView)}
                });
            }
        }

我的观点

<ListView Grid.Row="1" x:Name="MenuListPage" SeparatorVisibility="None" 
              HasUnevenRows="true" ItemsSource="{Binding MenuItems}" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <StackLayout Padding="15,10" HorizontalOptions="FillAndExpand">
                                <Label VerticalOptions="FillAndExpand" 
                                VerticalTextAlignment="Center" 
                                Text="{Binding Title, StringFormat='{0}',Source={x:Static translate:Translator.TranslatorInstance}}" 
                                FontSize="24"/>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

translationExtension类

/// <summary>
        /// Current culture info
        /// </summary>
        public static CultureInfo CultureInfoApp { get; private set; }

        // Path of folder where is store each file language + Name of file without .en ( language code ) 
        private const string ResourceId = "Landauer.Mobile.Ressources.Language.LanguageRessource"; 

        // Instanciation differed of Ressourcemanager
        public static readonly Lazy<ResourceManager> RessourceManagerLanguage = new Lazy<ResourceManager>(() => new ResourceManager(ResourceId, IntrospectionExtensions.GetTypeInfo(typeof(TranslateExtension)).Assembly));

        /// <summary>
        /// Match to the name of the label into .resx file
        /// </summary>
        public string Text { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="text"></param>
        public TranslateExtension()
        {
            if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
            {
                // Get dependency in each specific platform
                CultureInfoApp = DependencyService.Get<ILanguage>().GetCurrentCultureInfo();
            }
            //Text = text;
        }

        object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
        {
            return ProvideValue(serviceProvider);
        }

        public BindingBase ProvideValue(IServiceProvider serviceProvider)
        {
            var binding = new Binding
            {
                Mode = BindingMode.OneWay,
                Path = $"[{Text}]",
                Source = Translator.TranslatorInstance,
            };
            return binding;
        }

最后是我的翻译班:

public static Translator TranslatorInstance => _uniqueInstance;

        /// <summary>
        /// When TranslateExtension you create new Binding(), call this "Callback"
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string this[string text]
        {
            get
            {
                return TranslateExtension.RessourceManagerLanguage.Value.GetString(text, TranslateExtension.CultureInfoApp);
            }
        }

        /// <summary>
        /// Implementation of notifications
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// At each time you set language use this method to refresh UI
        /// </summary>
        public void Invalidate()
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
        }

1 个答案:

答案 0 :(得分:0)

更改语言时,您需要设置资源的区域性。

您的语言实例类还应该在设置区域性时调用属性更改处理程序。

因此请在下面的实例类中创建一个方法,并在更改语言设置时调用。.

public void SetCultureInfo(CultureInfo cultureInfo)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(null));
    }

更改语言时,代码应如下所示

var ci = CultureInfo.CreateSpecificCulture("ar");
                NativeLangUtil.SetLocale(ci); // updating Native 
                Resx.Lang.Strings.Culture = ci; //For .net Resources to work
                Application.Current.Properties["Lang"] = ci.TwoLetterISOLanguageName;// 
                LangResourceLoader.Instance.SetCultureInfo(ci); //for our use

您可以找到sample implementation here