本文介绍了自动INotifyPropertyChanged的通过T4 code系列实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在建立我的一个新的项目,并想知道我怎么能实现,而不必手工code所有属性我自己,我的ViewModel类的确存在INotifyPropertyChanged的支持。

I'm currently working on setting up a new project of mine and was wondering how I could achieve that my ViewModel classes do have INotifyPropertyChanged support while not having to handcode all the properties myself.

我看着AOP框架,但我认为他们只会炸掉我的项目与其他依赖。

I looked into AOP frameworks but I think they would just blow up my project with another dependency.

于是我想到了用T4生成属性的实现。

So I thought about generating the property implementations with T4.

的设置是这样的:我有一个声明只是它的属性背景变量,然后我用T4从它生成的属性实现的ViewModel类

The setup would be this: I have a ViewModel class that declares just its Properties background variables and then I use T4 to generate the Property Implementations from it.

例如,这将是我的视图模型:

For example this would be my ViewModel:

public partial class ViewModel
{
    private string p_SomeProperty;
}

然后T4会去在源文件并查找名为P_的成员声明,​​并产生这样的文件:

Then T4 would go over the source file and look for member declarations named "p_" and generate a file like this:

public partial class ViewModel
{
    public string SomeProperty
    {
        get
        {
            return p_SomeProperty;
        }
        set
        {
            p_SomeProperty= value;
            NotifyPropertyChanged("SomeProperty");
        }
    }
}

该方法有一定的优势,但我不知道它是否能真正发挥作用。所以我想在这里发表我的想法在计算器上作为一个问题提出来得到它的一些反馈,也许一些建议如何可以做的更好/更容易/更安全。

This approach has some advantages but I'm not sure if it can really work. So I wanted to post my idea here on StackOverflow as a question to get some feedback on it and maybe some advice how it can be done better/easier/safer.

推荐答案

Here's一个伟大的职位由科林·埃伯哈特的对检查定制从Visual Studio与EnvDTE属性直接从T4产生依赖属性。它不应该是很难适应它来检查领域,产生code,因为适当的职位包含了一些简单实用的方法来浏览code节点。

Here's a great post by Colin Eberhardt on generating Dependency Properties from a T4 by inspecting custom attributes directly from Visual Studio with EnvDTE. It shouldn't be difficult to adapt it to inspect fields and generate code appropriately since the post contains simple utility methods to browse code nodes.

注意,使用VS T4的时候,你不应该在自己的组件使用反射,否则会被锁定,您将不得不重新启动Visual Studio以重建。

Note that when using T4 from VS, you shouldn't use Reflection on your own assemblies or they'll get locked and you'll have to restart Visual Studio in order to rebuild.

这篇关于自动INotifyPropertyChanged的通过T4 code系列实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 13:31