Search code examples
c#winui-3windows-template-studio

WinUI 3 TemplateStudio Read from local settings using the LocalSettingsService


i am using TemplateStudio for WinUi3 to create my app. Now I want to Read my local settings using the ILocalSettingsService integrated by the TemplateStudio but i get an error. Here's my code:

private void Page_Loaded(object sender, Microsoft.UI.Xaml.RoutedEventArgs e)
{
    var notifications = _settingsService.ReadSettingAsync<String>("notifiacations");
    var notificationsSound = _settingsService.ReadSettingAsync<String>("notifications.sound");

    if (notifications != null && notificationsSound != null)
    {
        if (notifications.Result.ToString() == "on")
        {
            NotificationToggle.IsOn = true;

        }
        else
        {
            NotificationToggle.IsOn = false;
        }

        if (notificationsSound.Result.ToString() == "on")
        {
            NotificationSoundToggle.IsOn = true;

        }
        else
        {
            NotificationSoundToggle.IsOn = false;

        }
    }
}

And the error:

System.NullReferenceException: "Object reference not set to an instance of an object." on this line of my code:

var notifications = _settingsService.ReadSettingAsync<String>("notifiacations");

I've already tried to leave the <string> but that didnt work


Solution

  • You need to get the service from the DI container.

    Try adding this line the page's constructor:

    _settingsService = App.GetService<ILocalSettingsService>();
    

    Then you'll be able to get the value:

    private async void SettingsPage_Loaded(object sender, RoutedEventArgs e)
    {
        var notifications = await _settingsService.ReadSettingAsync<string>("notifications");
    }