Skip to content

Interpolation Support for LocalizeEnumConverter #11

Description

@livonium

What problem would this solve?

Interpolation support for the enum Localizer could significantly reduce boilerplate in cases where the resource key itself depends on the state of the arguments being passed in (e.g. if some are set/null, whether some arguments are plural numerals or not, etc.)

For example, one may wish to support the following variations of displaying partitions, whose formats can differ per language (inline codeblocks represent interpolated arguments):

  • "Drive 2, Partition 1"
  • "F: Drive"
  • "My USB"
  • "My USB (F:)

Enums can be created on the C#-end whose values depend on the presence of some of the arguments. Currently, since LocalizeEnumConverter does not support arguments, one has to write custom generic or per-case bindings and/or converters which do accept model bindings as input, or rely on the viewmodel, which could potentially bloat it and make it harder to maintain.

Proposed solution

LocalizeEnumConverter.cs could be slightly modified to slice the rest of the values object array (sans 1 for the CurrentCulture binding) in Convert() into an argument array which can be passed to Localizer.Current.Get().

// LocalizeEnumConverter.cs
    public Object Convert(IList<Object?> values, Type targetType, Object? parameter, CultureInfo culture)
    {
        if (values.Count == 0 || values[0] is not Enum enumValue)
        {
            return String.Empty;
        }

        var key = EnumKeyConvention.BuildEnumKey(enumValue, this.KeyPrefix);

        var args = values.Skip(1).Take(values.Count - 2).ToArray();

        return this.ResourceManager is null
            ? (args is {Length: >0} ? Localizer.Current.Get(key, args) : Localizer.Current.Get(key))
            : (args is {Length: >0} ? Localizer.Current.Get(key, this.ResourceManager, args) : Localizer.Current.Get(key, this.ResourceManager));
    }

Alternatives considered

Currently, my project uses a modified version of LocalizeEnumConverter.cs (alongside a copy of the internal class EnumKeyConvention), which implements the modifications shown above. However, this approach feels like a band-aid solution to a feature currently missing in the enum Localizer, which the regular Localizer and extension already have. Furthermore, this approach requires upkeep if/when ResXLocalization updates, in order to implement new features and/or comply with any API changes.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions