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?
You can use the
Closedevent to call SaveStateAsync().