I need to capture old value, new value and property name in PropertyChanged event handler. The default implementation of INotifyPropertyChanged provides only name of the property. So after searching on internet, I found similar question here with Extended implementation of property changed.
Below is the link to that Q and interface declaration:
NotifyPropertyChanged event where event args contain the old value
public interface INotifyPropertyChangedExtended<T>
{
event PropertyChangedExtendedEventHandler<T> PropertyChanged;
}
public delegate void PropertyChangedExtendedEventHandler(object sender, PropertyChangedExtendedEventArgs e);
Above interface will solve my problem, however I am not understanding how to implement generic interface on my Entity class because T will change depending on data type of property.
Can anyone help me in understanding, will it be possible to implement this interface with T parameter. Sample implementation of this will be really helpful.
Thanks in advance for help.
Umesh
EDIT #1: Based on the reply from Peter, posting updated code that may be useful for someone who wants to capture old and new values in PropertyChanged event.
public class PropertyChangedExtendedEventArgs : PropertyChangedEventArgs
{
public string OldValue { get; set; }
public string NewValue { get; set; }
public PropertyChangedExtendedEventArgs(string propertyName, string oldValue, string newValue) : base(propertyName)
{
OldValue = oldValue;
NewValue = newValue;
}
}
//
// Summary:
// Notifies clients that a property value has changed.
public interface INotifyPropertyChangedEnhanced
{
//
// Summary:
// Occurs when a property value changes.
event PropertyChangedEventHandlerEnhanced PropertyChanged;
}
public delegate void PropertyChangedEventHandlerEnhanced(object sender, PropertyChangedExtendedEventArgs e);
public abstract class BindableBase : INotifyPropertyChangedEnhanced
{
public event PropertyChangedEventHandlerEnhanced PropertyChanged;
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName]
string propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
var oldValue = storage;
storage = value;
this.OnPropertyChanged(oldValue, value, propertyName);
return true;
}
protected void OnPropertyChanged<T>(T oldValue, T newValue, [CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedExtendedEventArgs(propertyName, oldValue?.ToString(), newValue?.ToString()));
}
}