INotifyPropertyChanged is a .NET interface used by a ViewModel to tell a bound View that one of its properties changed. It exposes a PropertyChanged event. When the View is bound to that property, it receives the event and updates the corresponding control. This is what lets MVVM update the UI without a ViewModel directly setting UI-control properties. section 9.3.4 section 9.7
Implement the interface on a ViewModel, declare the PropertyChanged event, and provide a helper that raises it with PropertyChangedEventArgs. A property setter changes its backing field and calls the helper. CallerMemberName can supply the calling property's name automatically, so setters can call OnPropertyChanged() without a string literal. section 9.1 section 9.5.2
A reusable base ViewModel
Put the shared implementation in BaseViewModel, then derive page-specific ViewModels from it. For example, Title and IsLoading use backing fields; each setter assigns the new value and invokes OnPropertyChanged(). An InputViewModel can inherit that behavior while adding commands, search results, a selected product, and a count. section 9.5.2
Use property-change notification when binding needs to reflect ViewModel state changes:
- Raise a notification after resetting bound input values such as a new to-do title or due date. section 9.1
- Raise a notification after updating state whose changed value the UI must display, such as a to-do collection. section 9.1
- Share the implementation through a base class when multiple ViewModels need common bindable state. section 9.5.2
Listing 9.7 BaseViewModel.cs
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace MauiStockTake.UI.ViewModels;
public class BaseViewModel : INotifyPropertyChanged #1
{
public event PropertyChangedEventHandler
PropertyChanged; #2
public void OnPropertyChanged([CallerMemberName]
string propertyName = "") #3
{
var changed = PropertyChanged; #4
if (changed == null)
return;
changed.Invoke(this, new PropertyChanged
EventArgs(propertyName)); #5
}
}
This implementation shows the essential event declaration and helper method that raises PropertyChanged with an inferred property name. section 9.5.2
INotifyPropertyChanged complements command binding rather than replacing it. Commands let a View invoke ViewModel functionality; PropertyChanged lets the View refresh bound values after ViewModel state changes. Together, they keep presentation logic in the ViewModel while the View displays and binds UI. section 9.3.4 section 9.7
