I want to observe a property of a class that did not implement INotifyPropertyChanged
.
Is there any way to achieve that? It would be great if I could create some generic class or base class to inherit from it and to work with.
I want to observe a property of a class that did not implement INotifyPropertyChanged
.
Is there any way to achieve that? It would be great if I could create some generic class or base class to inherit from it and to work with.
If you can't change your class where you need the event, you can use this wrapper:
public class NotifyPropertyChangedWrapper<T> : INotifyPropertyChanged
{
private readonly T item;
public event PropertyChangedEventHandler PropertyChanged;
public NotifyPropertyChangedWrapper(T item)
{
this.item = item;
}
public TProp Get<TProp>(Expression<Func<T, TProp>> exp)
{
MemberExpression memExp = exp.Body as MemberExpression;
var property = memExp.Member as PropertyInfo;
return (TProp)property.GetValue(item);
}
public void Set<TProp>(Expression<Func<T, TProp>> exp, TProp newValue)
{
MemberExpression memExp = exp.Body as MemberExpression;
var property = memExp.Member as PropertyInfo;
property.SetValue(item, newValue);
PropertyChanged?.Invoke(item, new PropertyChangedEventArgs(property.Name));
}
}
If you use it, you only set and get the properties via the wrapper's set and get methods. If you do so, the NotifyPropertyChanged
event will be invoked. Here is an example usage
class Test
{
public int SomeProperty { get; set; }
}
var notify = new NotifyPropertyChangedWrapper<Test>(new Test());
notify.PropertyChanged += (s, e) => Console.WriteLine(e.PropertyName);
notify.Set(x => x.SomeProperty, 10);
Console.WriteLine(notify.Get(x => x.SomeProperty));
Here is an online demo: https://dotnetfiddle.net/oVE4WW