Skip to content

Improvement: LocalizeExtension.cs #2

@SineVector241

Description

@SineVector241

Hi. I don't know if you're still updating this lib but there is a possible improvement that you could add to reduce memory and add the ability to translate using {Binding } variables.

The following is my modification that I am using in my own project. (You of course can modify it to work with your lib)

using System;
using System.Linq;
using Avalonia.Data;
using Avalonia.Data.Converters;
using Avalonia.Markup.Xaml;
using VoiceCraft.Core.Locales;

namespace VoiceCraft.Client.Locales;

public class LocalizeExtension(object arg) : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (arg is string key)
            return new Binding(nameof(Localizer.Instance.Language))
            {
                Source = Localizer.Instance,
                Mode = BindingMode.OneWay,
                Converter = new FuncValueConverter<string, string>(x => Localizer.Get(key))
            };

        if (arg is not IBinding binding)
            throw new Exception("Argument must be of type IBinding or string!");

        var mb = new MultiBinding
        {
            Bindings = [binding, new Binding(nameof(Localizer.Instance.Language)) { Source = Localizer.Instance }],
            Mode = BindingMode.OneWay,
            Converter = new FuncMultiValueConverter<string, string>(x => Localizer.Get(x.ElementAtOrDefault(0) ?? ""))
        };

        return mb;
    }
}

Binding Examples:

            <TextBlock Grid.Column="0"
                       Margin="10"
                       VerticalAlignment="Center"
                       FontSize="20"
                       FontWeight="Bold"
                       Text="{locale:Localize { Binding $parent[UserControl].((vm:HomeViewModel)DataContext).Title } }"
                       TextAlignment="Center" />

There probably is a cleaner way to bind but this is what I do...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions