SirJohnK/LocalizationResourceManager.Maui

Problem with properties

Closed this issue · 2 comments

Hi
I am using your nuget.
I have this in my viewmodel:

THIS WORKS!
public LocalizedString Versione { get; } = new(() => string.Format(AppResource.VersioneFmt, AppInfo.Version, AppInfo.BuildString));

THIS NOT WORKS
[ObservableProperty]
Config configurazione;

    public LocalizedString Utente { get; } = new(() => string.Format(AppResource.UtenteFmt, Configurazione.Utente));

I have a compile error

Gravità Codice Descrizione Progetto File Riga Stato eliminazione
Errore CS0236 Un inizializzatore di campo non può fare riferimento alla proprietà, al metodo o al campo non statico 'MainViewModel.Configurazione' Esselunga STR Mobile (net7.0-windows10.0.19041.0) C:\Soluzione1\Progetti\str_mobile\ViewModels\MainViewModel.cs 33 Attivo

Translated in:
A field initializer cannot refer to the property, method, or non-static field

Thanks

Hi,

Yes, as the error suggests, the field initializer cannot be set to a non-static field and Configurazione.Utente do not look like a static field.

To solve this, you can create your LocalizedString in the constructor.

Similar like this from the Sample project:

private readonly ILocalizationResourceManager resourceManager;

public LocalizedString HelloWorld { get; }

public MainPage(ILocalizationResourceManager resourceManager)
{
    InitializeComponent();
    this.resourceManager = resourceManager;

    HelloWorld = new(() => $"{resourceManager["Hello"]}, {resourceManager["World"]}!");

    BindingContext = this;
}

In your specific case, it would look something like this:

private readonly ILocalizationResourceManager resourceManager;

[ObservableProperty]
Config configurazione;

public LocalizedString Utente { get; }

public MainViewModel(ILocalizationResourceManager resourceManager)
{
    this.resourceManager = resourceManager;

    Utente = new(() => resourceManager["UtenteFmt", Configurazione.Utente]);
}

You could reference the AppResource directly:

Utente = new(() => string.Format(AppResource.UtenteFmt, Configurazione.Utente));

But, that will bypass the lookup by the LocalizationResourceManager, so I should recommend the first solution.

Excellent! Thanks