Skip to content

ViewModel Lifecycle Events #4

@aritchie

Description

@aritchie

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

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions