MVVM Toolkit is an amazing library when building .NET MAUI Apps with MVVM! Especially the MVVM source generators, that generates all that boiler plate code for INotifyPropertyChanged, Properties, Commands etc. With a couple of nifty Attributesand Classes you can easily add this to your code!

Like in this example for a base view model class:

/// <summary>
/// Base ViewModel.
/// </summary>
public partial class BaseViewModel : ObservableObject
{
    [ObservableProperty]
    private string title;
    
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(CanExecute))]
    private bool isBusy;

    public bool CanExecute => !IsBusy;
}

No WeakEventManager! The one thing that I miss from the Xamarin Community Toolkit is the WeakEventManager for safe handling of events! In .NET MAUI we have that WeakEventManager built in!

So I decided to extend the ObservableObject class in the MVVM Toolkit to add this! By inherting this class into a class called BaseObservableObject and implementing INotifyPropertyChanged and INotifyPropertyChanging events, I could override the EventHandler and intercept the events to use the WeakEventManager.

/// <summary>
/// Extended ObservableObject that uses WeakEventManager to avoid memory leaks!
/// </summary>
public class BaseObservableObject : ObservableObject, INotifyPropertyChanged, INotifyPropertyChanging
{
    private readonly WeakEventManager weakEventManager = new WeakEventManager();

    event PropertyChangedEventHandler? INotifyPropertyChanged.PropertyChanged
    {
        add => weakEventManager.AddEventHandler(value);
        remove => weakEventManager.RemoveEventHandler(value);
    }

    event System.ComponentModel.PropertyChangingEventHandler? INotifyPropertyChanging.PropertyChanging
    {
        add => weakEventManager.AddEventHandler(value);
        remove => weakEventManager.RemoveEventHandler(value);
    }

    public new event PropertyChangedEventHandler? PropertyChanged
    {
        add => weakEventManager.AddEventHandler(value);
        remove => weakEventManager.RemoveEventHandler(value);
    }

    public new event System.ComponentModel.PropertyChangingEventHandler? PropertyChanging
    {
        add => weakEventManager.AddEventHandler(value);
        remove => weakEventManager.RemoveEventHandler(value);
    }

    protected override void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        weakEventManager.HandleEvent(this, e, nameof(INotifyPropertyChanged.PropertyChanged));
    }

    protected override void OnPropertyChanging(System.ComponentModel.PropertyChangingEventArgs e)
    {
        weakEventManager.HandleEvent(this, e, nameof(INotifyPropertyChanging.PropertyChanging));
    }
}

So now by inherting the BaseObservableObject in our classes, we now have event handling with WeakEventManager in our code using the MVVM Toolkit!

public partial class BaseViewModel : BaseObservableObject