Search code examples
c#xamllocalizationmaui

Picker values localization in MAUI


What is a right way to localize picker values in MAUI? So far I have only one idea:

Use LocalizationResourceManager.Maui. But for picker values it doesn't work when app localization has been changed untill app restart.

<Picker
    x:Name="NativeLanguagePicker"
    ItemsSource="{Binding NativeLanguageSetting.Options}"
    SelectedItem ="{Binding NativeLanguageSetting.Picked, Mode=TwoWay}"
    ItemDisplayBinding="{localization:TranslateBinding Localization, TranslateValue=True}"
    Style="{DynamicResource SettingPicker}">
</Picker>

Is there any way to do it right in MAUI? Because the whole app follows culture change and translates accordingly except of pickers. It looks like there should be a way to do it elegantly.


Solution

  • I posted an answer to your issue on the maui discussion https://github.com/dotnet/maui/discussions/25329.

    The problem is that Picker.ItemDisplayBinding is caching its results so it will not see the changes coming from the Binding. To tickle it, update Picker.ItemDisplayBinding itself. I did this by porting your TranslateBinding to the view model as follows.

    ItemDisplayBinding="{Binding DisplayBinding}"
    

    Then whenever the language changes I raise OnPropertyChanged(nameof(DisplayBinding)). The implementation of DisplayBinding in your view model becomes like this:

        public BindingBase DisplayBinding { get; } = new Binding("Localization", converter: new TranslateConverter());
        internal class TranslateConverter : IValueConverter
        {
            public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)
                => (value is string s) ? PickerLocalizationIssue.Resources.Localization.AppResources.ResourceManager.GetString(s) : null;
            public object? ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture)
                => throw new NotImplementedException();
        }
    

    Have a look at the PR I raised: https://github.com/AncientLust/PickerLocalizationIssue/pull/1