-
-
Notifications
You must be signed in to change notification settings - Fork 228
Implementing An IsChanged Flag
Lucas Trzesniewski edited this page Aug 7, 2023
·
4 revisions
A common scenario around INotifyPropertyChanged
is the use of an “IsChanged” flag. This could be used to help decide if an object needs to be saved back to a database.
This can be done in the following way.
public class Person : INotifyPropertyChanged
{
public string Name { get; set; }
public bool IsChanged { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
}
public class Person : INotifyPropertyChanged
{
string name;
bool isChanged;
public string Name
{
get => name;
set
{
if (name != value)
{
name = value;
IsChanged = true;
OnPropertyChanged(InternalEventArgsCache.Name);
}
}
}
public bool IsChanged
{
get => isChanged;
set
{
if (isChanged != value)
{
isChanged = value;
OnPropertyChanged(InternalEventArgsCache.IsChanged);
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(PropertyChangedEventArgs eventArgs)
{
PropertyChanged?.Invoke(this, eventArgs);
}
}
You will notice that IsChanged
is set to true
inside the setter of Name
.
Note that after "saving/persisting" the object it is your responsibility to set the IsChanged
property back to false.