C# WPF How to set Property setter method dynamically?

与世无争的帅哥 提交于 2019-12-05 09:01:15

What you are looking for has been solved in the concept of Aspect Oriented Programming (AOP).

One example is in PostSharp, (Also, see details here) which lets you write your data/viewmodel classes like this:

[NotifyPropertyChanged]
public class Shape
{
    public double X { get; set; }
    public double Y { get; set; }
}

public class Rectangle : Shape
{
    public double Width { get; set; }
    public double Height { get; set; }
}

If you don't like PostSharp, I'm sure the other AOP frameworks out there has similar functionality.

EDIT

I just found NotifyPropertyWeaver which does this for you without requiring a full AOP framework.

It uses the Mono.Cecil stuff to inject notification code during compilation and is installable either through NuGet (this is what I did) or from the project web site.

By default, it doesn't even require attributes, (it automatically figures out which properties and classes need change notification) but you can be explicit also, like so:

[NotifyProperty]
public int FooBar { get; set; }

One nice feature I found in it was the possibility to declare dependencies between properties. In this case, RaisePropertyChanged("FoobarTimesTwo") will be called whenever FooBar changes.

[DependsOn("FooBar")]
public int FoobarTimesTwo
{
    get { return FooBar * 2; }
}

In addition to AOP frameworks like PostSharp there are also such things as:

Mono.Cecil

With that tool you can take an assembly, modify it's code and save it back

There are some articles of LinFu about AOP which may help

LinFu Articles on CodeProject

The open source framework ImpromptuInterface.MVVM uses the C# 4.0 dynamic features to add automatic properties that support property changed. It's ImpromptuViewModel works like an ExpandoObject but also has other features to help with MVVM.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!