How can i save my app state on closing the application with WinUI 3

255 Views Asked by At
public partial class MainViewModel : ObservableObject, INavigationAware
{
    public async void OnNavigatedTo(object parameter)
    {
        await RestoreStateAsync();
    }

    public async void OnNavigatedFrom()
    {
        await SaveStateAsync();
    }

    [RelayCommand]
    private async Task SaveStateAsync()
    {
        var path = Path.Combine(
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "",
            "main_view_model_state.json");

        using FileStream fileStream = new(path, FileMode.Create);

        await JsonSerializer.SerializeAsync(
            fileStream, 
            this,
            new JsonSerializerOptions
            {
                IgnoreReadOnlyProperties = true,
            });
    }


    [RelayCommand]
    private async Task RestoreStateAsync()
    {
        var path = Path.Combine(
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "",
            "main_view_model_state.json");

        using FileStream fileStream = new(path, FileMode.Open);

        var state = await JsonSerializer.DeserializeAsync<MainViewModel>(fileStream);

        if(state == null)
        {
            return;
        }

        ChannelSource = state.ChannelSource;
        Selected = state.Selected;
    }
}

I want to automaticly save and restore the state of my ViewModel with these functions. Restoring the state works when the application gets launched, but when i close the app "OnNavigatedFrom" is not called. Is there another function that gets called, when the app is closed?

Any suggestions?

1

There are 1 best solutions below

2
Andrew KeepCoding On BEST ANSWER

You can use the Closed event to call SaveStateAsync().

public sealed partial class MainWindow : Window
{
    public MainWindow()
    {
        this.InitializeComponent();
        this.Closed += MainWindow_Closed;
    }

    public ViewModel ViewModel { get; } = new();

    private async void MainWindow_Closed(object sender, WindowEventArgs args)
    {
        // Navigate to another page, for example, to the "SettingsPage",
        // so the "OnNavigatedFrom()" gets called.
        App.GetService<INavigationService>()
               .NavigateTo(typeof(SettingsViewModel)
               .FullName!);
    }   
}