csharpfritz / csharpfritz/MauiWorkshop

ViewModel Lifecycle Events

Open
#4 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
C#
Stars
47
Forks
4
PR merge metrics
No merged PRs in 30d

Description

https://github.com/csharpfritz/MauiWorkshop/blob/155283ecb14e12968cb677252514aead83b863b7/src/MyNewsReader/ViewModels/NewsFeedListViewModel.cs#L17

This is a gap in the .NET MAUI functionality. The lack of a true "OnStart/OnNavigatedTo/etc" really makes things like this difficult for users, so they put running code inside the constructor. This can cause several issues:
* Properties like IsBusy can be missed due to timing because the view isn't ready yet.
* If an error happens, sometimes devs like to show a dialog "Hey user, are http request timed out", but if they show this dialog before the view is ready - the app can crash.

3rd party libraries like https://prismlibrary.com/ cover this gap perfectly by mapping up the page lifecycle to an interface marked viewmodel.

In this case and for the sake of new users, I suggest adding a "virtual OnNavigatedTo()" to your baseviewmodel and having your pages call it using something like

```csharp
public abstract class BaseContentPage : ContentPage
{
protected override void OnNavigatedTo(NavigatedToEventArgs args)
{
base.OnNavigatedTo(args);

(BindingContext as BaseViewModel)?.OnNavigatedTo();
}
}
```

Happy to send a PR for this.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.