问题
I have found an implementation of Propperty Changed Event, where i can Call Property changed without the Name of the Property in the web. And then i have build a Extension Method with it wich is here
public static void OnPropertyChanged(this INotifyPropertyChanged iNotifyPropertyChanged, string propertyName = null)
{
if (propertyName == null)
propertyName = new StackTrace().GetFrame(1).GetMethod().Name.Replace("set_", "");
FieldInfo field = iNotifyPropertyChanged.GetType().GetField("PropertyChanged", BindingFlags.Instance | BindingFlags.NonPublic);
if (field == (FieldInfo) null)
return;
object obj = field.GetValue((object) iNotifyPropertyChanged);
if (obj == null)
return;
obj.GetType().GetMethod("Invoke").Invoke(obj, new object[2]
{
(object) iNotifyPropertyChanged,
(object) new PropertyChangedEventArgs(propertyName)
});
}
So i can call Property changed like this:
private bool _foo;
public bool Foo
{
get { _foo; }
private set
{
_foo = value;
this.OnPropertyChanged();
}
}
But I thought, it would be nicer if i don't have to implement the getter and setter of a Property when i use Property changed.
Does anyone now how to implement the OnPropertyChanged Method as Attribute, maybe with AOP?
So that Auto-Property can be used for Property Changed like this:
[OnPropertyChanged]
public bool Foo {set;get;}
回答1:
Check out Fody, and the PropertyChanged add-in. It will modify the IL after compilation to add the code to raise the PropertyChanged
event for your properties. It's similar to PostSharp, mentioned in Lasse's answer, but it's free and open-source.
回答2:
You will need some kind of AOP system to do this.
Either something where you wrap or inherit from your class, and dynamically generate the necessary plumbing in the wrapper/descendant to handle this, or some system like Postsharp that rewrites your code after compilation.
There is nothing built into .NET to handle this.
来源:https://stackoverflow.com/questions/25200516/is-it-possible-to-implement-property-changed-as-attribute