INotifyPropertyChanged - 自动属性的功能 [英] INotifyPropertyChanged-Feature on Auto-Properties

查看:710
本文介绍了INotifyPropertyChanged - 自动属性的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多模型类,它们实现INotifyPropertyChanged接口,以便在值改变时更新UI。

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

很遗憾,属性必须完全写入才能支持特征。我通过使用BaseClass中的SetPropertyValue方法()减少了我的代码。

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 ); }
}

但是在一个文件中写入20个属性不是那么简单

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; }

我已经选中了 PostSharp ,但在免费版本只有10类包括(这是一个爱好项目,所以我不想支付很多钱)。

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).

有没有可能将我的一个逻辑附加到C#-Compiler(作为预编译器)?
这样的功能我想在我的代码中的不同地方使用,以减少不必要的编码行(特别是对于自动属性)。

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).

或者maybee一个VisulStudio -Extension?

Or maybee a VisulStudio-Extension?

推荐答案

尝试 Fody 。它是在编译过程中使用专用msbuild任务修改IL代码的库。

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

它有大量的addins,包括 PropertyChanged ,这应该适合您的场景。
此插件提供了属性ImplementPropertyChanged,您可以将其应用于类。然后Fody将生成实现INotifyPropertyChanged到所有自动属性的代码。

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.

第二个选项,如果您有ReSharper版本7或更高版本。它有重构,可以帮助您实现INotifyPropertyChanges。例如,它可以将自动属性转换为实现接口的正常属性。
它可能不完全满足你 - 这种方法可能是有趣的,因为它不涉及额外的库和程序集修改。

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.

这篇关于INotifyPropertyChanged - 自动属性的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆