I am implementing INotifyPropertyChanged
on some viewmodels in a WPF project. For this I need to always declare INotifyPropertyChanged
specific code like in the following example:
class ViewModel : INotifyPropertyChanged
{
private bool _property;
public event PropertyChangedEventHandler PropertyChanged;
public bool Property
{
get { return _property; }
set
{
_property = value;
OnPropertyChanged("Property");
}
}
protected virtual void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
The only code that is specific to ViewModel
is the Property
while the rest seems to me to be only noise. I have tried to reduce it, considering that I don't have only one viewmodel and that in future there will be more added, by adding an abstract class between the viewmodels and the INotifyPropertyChanged
interface this way:
public abstract class NotifiableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Now all the viewmodels got much shorter, for example:
class ViewModel : NotifiableObject
{
private bool _property;
public bool Property
{
get { return _property; }
set
{
_property = value;
NotifyPropertyChanged(nameof(Property));
}
}
}
Now for every property that I will add, I will not be able to use auto-property, but instead I will have to keep a backed field and always on the setter I will have to call NotifyPropertyChanged
method. I am looking for a way to avoid this and reduce my code even further to something like:
class ViewModel : NotifiableObject
{
[NotifiableProperty]
public bool Property { get; set; }
}
I am not looking especially for an attribute since it has been asked before related to WPF or related to C# in general, but for any way to work around this issue.
I know that the code is shorter now, but in future this will have a great impact over the readability of the application. Any improvement suggestion is appreciated.
Thank you!