The best way to implement INotifyPropertyChanged in .NET Maui

This is the best way that I've discovered to implement INotifyPropertyChanged in a XAML based MVVM app without downloading any extra supporting code.

It relies on the ref keyword to allow a method in the base class to modify the property that you wish to raise a property changed event for. The code is fairly concise and it doesn't add any unseen overhead.

In your view model all you need to do is:

namespace Nogginbox.MyApp.ViewModels;

public class MyViewModel : ObservableViewModelBase
{
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value);
    }
    private string _name;
}

This relies on this fairly simple base class:

using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace Nogginbox.MyApp.ViewModels;

public abstract class ObservableViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));

    /// <summary>    /// Set a property and raise a property changed event if it has changed
    /// </summary>    protected bool SetProperty<T>(ref T property, T value, [CallerMemberName] string propertyName = null)
    {
        if (EqualityComparer<T>.Default.Equals(property, value))
        {
            return false;
        }

        property = value;
        RaisePropertyChanged(propertyName);
        return true;
    }
}

And that's it! Not quite as nice a normal auto property setter, but not that much more code.