I have a simple WPF application and I would like to know why NotifyOfPropertyChange() is not working as I expect. I have a MainWindowViewModel with two properties and one button, and when I click the button I call NotifyOfPropertyChange() to notify that all the properties have changed. I also have a list of properties compiled in the ViewModel constructor:
properties = typeof(MainWindowViewModel).GetProperties()
.Where(p => p.DeclaringType == typeof(MainWindowViewModel));
In the constructor, I have subscribed to PropertyChanged:
PropertyChanged += (sender, args) =>
{
if (properties.Any(p => p.Name == args.PropertyName))
IsDirty = true;
};
Here is my entire MainViewModel:
public class MainWindowViewModel : Screen
{
private string name;
private IEnumerable<PropertyInfo> properties;
public string Name
{
get { return name; }
set
{
name = value;
NotifyOfPropertyChange(() => Name);
}
}
private int age;
public int Age
{
get { return age; }
set
{
age = value;
NotifyOfPropertyChange(() => Age);
}
}
private bool isDirty;
public bool IsDirty
{
get { return isDirty; }
set
{
isDirty = value;
NotifyOfPropertyChange(() => IsDirty);
}
}
public MainWindowViewModel()
{
// get list of class properties
properties = typeof(MainWindowViewModel).GetProperties()
.Where(p => p.DeclaringType == typeof(MainWindowViewModel));
// if any property has been updated, set isDirty to true
PropertyChanged += (sender, args) =>
{
if (properties.Any(p => p.Name == args.PropertyName))
IsDirty = true;
};
}
public void Save()
{
NotifyOfPropertyChange();
}
}
When the application runs, the constructor correctly produces the list of properties: Name, Age and IsDirty. However, when the Save button is clicked, the PropertyChangedEvent is raised for other properties not associated with the viewmodel: IsInitialized, and IsActive, which are properties of screen, and is not raised for any properties in the list. Can someone tell me what is going on here or give an alternate solution? I think its pretty clear what I'm trying to do, this is a validation scenario, and I need to call a PropertyChanged and set a flag if the save button is clicked, so that all properties can be validated.