JSEDLAK » Blog Archive » FGF: A Base Class For INotifyPropertyChanged

FGF: A Base Class For INotifyPropertyChanged

One piece of functionality I consistently find myself writing and rewriting is the implementation of the INotifyPropertyChanged interface. This class, located in the main FGF library, makes that rewriting unnecessary by implementing it in an open way.

?View Code CSHARP
1
2
3
4
5
public class NotifyPropertyChangedBase : INotifyPropertyChanged
{
    private bool isDirty = false;
 
    public event PropertyChangedEventHandler PropertyChanged;

A virtual method is then added to allow end developers to change how the class reacts to when properties are changed.

?View Code CSHARP
1
2
3
4
    protected virtual bool CanSetDirty()
    {
        return !DisableDirtyFlag;
    }

To fire the event, a simple method is written that can be used by end developers. This method makes a call to a virtual method that actually fires the event and sets the IsDirty property.

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
    protected void OnPropertyChanged(string propertyName)
    {
        OnPropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
 
    protected virtual void OnPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        if (args.PropertyName != "IsDirty")
            IsDirty = true;
 
        if (PropertyChanged != null) PropertyChanged.Invoke(sender, args);
    }

And finally the properties:

?View Code CSHARP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    public bool DisableDirtyFlag { get; set; }
 
    public bool IsDirty
    {
        get { return isDirty; }
        set
        {
            if (CanSetDirty())
            {
                isDirty = value;
 
                OnPropertyChanged("IsDirty");
            }
        }
    }
}

Leave a Reply