Home > other >  Possible way to reduce translation properties with MVVM in WPF
Possible way to reduce translation properties with MVVM in WPF

Time:04-07

I'm doing refactoring for our app. We currently have 2 languages supported, where the logic is sitting inside TranslationService, injected through DI container (using Prism if matters) into View models.

In order to bind the translation to the text property there is tons of properties in the view model, e.g.

public string SomeText => _translationService.GetTranslation("someText");

public string AnotherText => _translationService.GetTranslation("notherText");

And the binding is happening as usual

<TextBlock Text="{Binding SomeText}" HorizontalAlignment="Center" />

Is there a way to reduce those properties? For example to bind the Text property to the GetTranslation method with a parameter?

I've seen how to use ObjectDataProvider but this doesn't really help me out, because the method parameters are hard-coded as per my understanding.

CodePudding user response:

You may declare a helper class with a single indexer property like

public class Translation
{
    private readonly TranslationService translationService;

    public Translation(TranslationService service)
    {
        translationService = service;
    }

    public string this[string key]
    {
        get { return translationService.GetTranslation(key); }
    }
}

which would be used as a single property in your view model:

public class ViewModel
{
    public ViewModel()
    {
        Translation = new Translation(_translationService);
    }

    public Translation Translation { get; }
}

You would bind it like this:

<TextBlock Text="{Binding Translation[someText]}"/>
  • Related