I use the same logic in my project. I have a base class for all view models in my app:
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class PropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Every view model inherits from this class. Now, in the setter of each property I just need to call OnPropertyChanged()
.
public class EveryViewModel : PropertyChangedBase
{
private bool initialized;
public bool Initialized
{
get
{
return initialized;
}
set
{
if (initialized != value)
{
initialized = value;
OnPropertyChanged();
}
}
}
Why does it work?
[CallerMemberName]
is automatically populated by the compiler with the name of the member who calls this function. When we call OnPropertyChanged
from Initialized
, the compiler puts nameof(Initialized)
as the parameter to OnPropertyChanged
Another important detail to keep in mind
The framework requires that PropertyChanged
and all properties that you're binding to are public
.
set { SetField(ref name, value); }
. TheSetField
method was shown in full. – Swag