Having used properties in an ObservableCollection, you are probably familiar with implementing INotifyPropertyChanged in your custom objects.
A property utilizing this implementation would look like this:
private string phoneNumberValue = String.Empty;
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
if (value != this.phoneNumberValue)
{
this.phoneNumberValue = value;
NotifyPropertyChanged("PhoneNumber");
}
}
}
To remedy this repetitive implementation, I created this:
/// <summary>
/// Extends the INotifyPropertyChanged interface to the class properties.
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged
{
#region Methods
/// <summary>
/// To be used within the "set" accessor in each property.
/// This invokes the OnPropertyChanged method.
/// </summary>
/// <typeparam name="T"></param>
/// <param name="name"></param>
/// <param name="value"></param>
/// <param name="newValue"></param>
protected void SetValue&amp;amp;amp;lt;T&amp;amp;amp;gt;(string name, ref T value, ref T newValue)
{
if (newValue != null)
{
if (!newValue.Equals(value))
{
value = newValue;
OnPropertyChanged(name);
}
}
else
{
value = default(T);
}
}
#endregion
#region INotifyPropertyChanged
/// <summary>
/// The PropertyChanged event handler.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Calls the PropertyChanged event
/// </summary>
/// <param name="propertyName"></param>
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
Then, all we need to do is inherit ViewModelBase in our custom object.
Now, our property would look something like this:
private string phoneNumberValue = String.Empty;
public string PhoneNumber
{
get
{
return this.phoneNumberValue;
}
set
{
SetValue("PhoneNumber", ref this.phoneNumberValue, ref value);
}
}
So, what was the reason for doing this?
- It avoids directly implementing INotifyPropertyChanged. This allows the ability to start up objects with this implementation much faster.
- Less coding and potential messes involving the set operator.
Update as of August 2022
Good news is since all the C# goodness over the last 10 years, I have greatly improved this implementation. It can be used like this:
private string _phoneNumberValue = String.Empty;
public string PhoneNumber
{
get => _phoneNumberValue;
set => NotifyOfChange(value, ref _phoneNumberValue);
}
Simple, right?