I've tried to code a class to avoid a method like "RaisePropertyChanged". I know that I can inherit from a class that has that implementation but in some cases I can't. I've tried with a Extension Method but Visual Studio complain.
public static class Extension
{
public static void RaisePropertyChanged(this INotifyPropertyChanged predicate, string propertyName)
{
if (predicate.PropertyChanged != null)
{
predicate.PropertyChanged(propertyName, new PropertyChangedEventArgs(propertyName));
}
}
}
It said:
"The event 'System.ComponentModel.INotifyPropertyChanged.PropertyChanged' can only appear on the left hand side of += or -="
Reed is right. However, I see what you're trying to do (make your code reusable—good for you); and I'll just point out that this is often easily rectified by accepting the PropertyChangedEventHandler
delegate itself and passing it from within the INotifyPropertyChanged
implementation:
public static void Raise(this PropertyChangedEventHandler handler, object sender, string propertyName)
{
if (handler != null)
{
handler(sender, new PropertyChangedEventArgs(propertyName));
}
}
Then from within your class which implements INotifyPropertyChanged
, you can call this extension method like so:
PropertyChanged.Raise(this, "MyProperty");
This works because, as Marc said, within the class declaring the event you can access it like a field (which means you can pass it as a delegate argument to a method, including extension methods).