SirJohnK / LocalizationResourceManager.Maui

Enhanced .NET MAUI version of the XCT LocalizationResourceManager.
MIT License
144 stars 12 forks source link

Use from ViewModels not having a dependency on MAUI? #22

Open hansmbakker opened 10 months ago

hansmbakker commented 10 months ago

I have my solution split in several projects where my project containing a ViewModels does not have a dependency on MAUI - just on the MVVM Community Toolkit.

Is there a way to access the ILocalizationResourceManager from ViewModels without taking a dependency on MAUI via LocalizationResourceManager.Maui?

E.g. in this example app, the MAUI dependent parts of localization and the view-agnostic parts of localization are put in separate projects so that the ViewModels can reference just the interface.

I see I could create a kind of wrapper pair (interface + implementation) myself, but it would be great to have this in the library!

hansmbakker commented 2 months ago

@SirJohnK would be curious to hear your thoughts on this! Am happy to create a PR that extracts the interfaces into a LocalizationManager.Core project, which is referenced by the LocalizationManager.Maui project if that helps (it will need a separate nuget package as well then).

SirJohnK commented 2 months ago

@hansmbakker , I like the idea to extract the ILocalizationResourceManager interface to enable reference without the dependency on MAUI!

Solution:

I will look into this tonight. 😄

SirJohnK commented 2 months ago

@hansmbakker , I think I have found a really nice solution for this! 😄

So now you can do this ViewModel with only help from MVVM Community Toolkit:

using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using LocalizationResourceManager.Maui.Core;

namespace LocalizationResourceManager.Maui.Sample.Common;

public partial class MainViewModel : ObservableObject
{
    public LocalizedString HelloWorld { get; }
    public LocalizedString CurrentCulture { get; }

    public MainViewModel(ILocalizationResourceManager resourceManager)
    {
        //Init
        HelloWorld = resourceManager.CreateLocalizedString(() => $"{resourceManager["Hello"]}, {resourceManager["World"]}!");
        CurrentCulture = new(resourceManager, () => resourceManager.CurrentCulture.NativeName);
    }

    [ObservableProperty]
    private int count;

    [RelayCommand]
    private void CounterClicked() => Count++;
}

What do you think?

hansmbakker commented 2 months ago

That looks good! Great!

SirJohnK commented 2 months ago

@hansmbakker, if you have the time, please test it out and report back your findings. Would be great to have some feedback before I will go live with this version!