INotifyPropertyChanged-Feature on Auto-Properties

眉间皱痕 提交于 2019-12-25 03:16:00

问题


I have many Model-Classes which implement the INotifyPropertyChanged-Interface in order to update the UI when value changed.

Sadly the properties must be written fully to support this feature. I decreased my code already by using the 'SetPropertyValue'-Method() in BaseClass.

private string _title;
public string Title 
{
    get { return title; }
    set { SetPropertyValue("Title", ref _title, value ); }
}

But with 20 properties written like that in one file it is not so simple to understand the content of the file in a short time unlike to the auto implemented properties.

What I want is to write my Property like this:

[NotifyChanged]
public string Title { get; set; }

I checked already PostSharp but in the free version there are only 10 classes included (it's a hobby project so I don't want to pay much money).

Is there any possibility to attach my one logic to C#-Compiler (as a pre-compiler)? Such a feature I would like to use on different places in my code to reduce unneccessary coding lines (especially for auto-properties).

Or maybee a VisulStudio-Extension?


回答1:


Try Fody. It is library which modifies IL code during build process using dedicated msbuild task.

It has large base of addins including PropertyChanged which should suit in your scenario. This addin gives you attribute ImplementPropertyChanged which you can apply to a class. Then Fody will generate code implementing INotifyPropertyChanged to all auto-properties.

Second option if you have ReSharper version 7 or higher. It has refactoring which can help you with implementation of INotifyPropertyChanges. For example it can transform auto-property to "normal" property implementing the interface. Thou it may not fully satisfy you - this approach may be interesting for you because it does not involve additional libraries and assembly modification.




回答2:


Another option is Castle DynamicProxy. The difference between PostSharp and Fody is that DynamicProxy generates its proxies on the fly at runtime.



来源:https://stackoverflow.com/questions/30103421/inotifypropertychanged-feature-on-auto-properties

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