Search code examples
c#.netuwpwinui-3winui

ColorPicker localization change in WinUI 3


I have a question, is there any way to update ColorPicker xaml element in WinUI3 when there's runtime language change in application without restart?

I tried to change Language property in ColorPicker, but language of it hadn't changed a bit.


Solution

  • AFAIK, the built-in localization won't update those labels unless you restart the app. Instead, you can localize them by yourself:

    private Dictionary<string, string> EnglishToSpanishDictionary { get; } = new()
    {
        { "Red", "Rojo" },
        { "Green", "Verde" },
        { "Blue", "Azul" },
        { "Hue", "Matiz" },
        { "Saturation", "Saturación" },
        { "Value", "Valor" },
        { "Opacity", "Opacidad" },
    };
    
    private void ColorPicker_Loaded(object sender, RoutedEventArgs e)
    {
        if (sender is not ColorPicker colorPicker)
        {
            return;
        }
    
        LocalizeColorPicker(colorPicker, EnglishToSpanishDictionary);
    }
    
    private static void LocalizeColorPicker(ColorPicker colorPicker, Dictionary<string, string> dictionary)
    {
        if (colorPicker.FindDescendants().OfType<TextBlock>() is not { } textBlocks)
        {
            return;
        }
    
        foreach (var textBlock in textBlocks)
        {
            if (dictionary.TryGetValue(textBlock.Text, out string? localizedString) is false ||
                string.IsNullOrEmpty(localizedString) is true)
            {
                continue;
            }
    
            textBlock.Text = localizedString;
        }
    }
    

    The FindDescendants extension comes from the CommunityToolkit.WinUI.Extensions NuGet package.

    Also, if you need runtime localization, check the WinUI3Localizer NuGet package. (I'm the author;))