1
I am creating a C# application and I am using the interface INotifyPropertyChanged thus:
public class Test: INotifyPropertyChanged
{
private int foo;
public int Foo { get => foo; set => Set(ref foo, value); }
public void Set<T>(ref T property, T value, [CallerMemberName]string p = "")
{
property = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(p));
}
}
My problem is that whenever I want to implement this way of working (with the method Set(ref property, value) i am obliged to come here and copy the code and reimplementit. From this problem, I thought of an extension method like this:
using System.Runtime.CompilerServices;
public static class Extensions
{
public static void Set<T>(
this INotifyPropertyChanged source, ref T property, T value,
[CallerMemberName]string propertyName = "")
{
property = value;
source.PropertyChanged?
.Invoke(source, new PropertyChangedEventArgs(propertyName));
}
}
My problem is that if I try to do this implementation, I get this message:
The Event
INotifyPropertyChanged.PropertyChangedcan only appear on the left hand side of += or -=
What I need to do to get me to force the call from that event through an extension property?
Tried to call as
this.? Or without the extension syntax and call the static method normally, until passing thethis?– Maniero
Hmm I haven’t tried... I’ll do it here, 1 me...
– LeandroLuk
It really doesn’t work... if I play a
thisthere he understands that I am trying to reference the static classExtensions. I would have to call the event within source– LeandroLuk
Why don’t you make a base class, say,
MyPropertyChanged, implements the functionSetin it and when you need it, rather than implementingINotifyPropertyChangedyou inherit fromMyPropertyChangedwhere the function already existsSetdefined. So it is usually done in the MVVM templates where you have aBaseViewModelwhere you implement only once theINotifyPropertyChanged– Kevin Kouketsu