INotifyPropertyChanged用于模型和视图模型 [英] INotifyPropertyChanged for model and viewmodel

查看:90
本文介绍了INotifyPropertyChanged用于模型和视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前不在家(还要待几周),只有一台平板电脑-因此,我无权使用Visual Studio来测试我要学习的内容-MVVM模式.

I am currently away from home (and will be for a few more weeks) and only have a tablet - therefore, I have no access to Visual Studio to test what I'm trying to learn - the MVVM pattern.

到目前为止,我认为理论已经确定,但是我对INotifyPropertyChanged界面感到困惑.

So far, I think the theory is set, but I'm confused about the INotifyPropertyChanged interface.

我认为MVVM模式的想法之一是能够更新Model,后者又通知ViewModel,后者又通知视图.如果我错了,那么这个问题的其余部分将毫无意义.

I think one of the ideas of the MVVM pattern is to be able to update the Model which in turn notifies the ViewModel which in turn notifies the view. If I'm wrong then the rest of this question is meaningless.

我的问题是,所有的类都必须共享INotifyPropertyChanged的1个实现吗?

My question is, do all the classes have to share 1 implementation of INotifyPropertyChanged?

换句话说,这是正确的:

In other words, which is correct:

  1. 所有类的属性名称都相同(但每个类都有其自己的INotifyPropertyChanged唯一实现)

所有类的属性名称都相同(并且每个类都继承自实现INotifyPropertyChanged的单个基类)?

A property name is the same for all classes (and each class inherits from a single base class which implements INotifyPropertyChanged)?

推荐答案

不,他们不必共享任何东西.但是,INotifyPropertyChanged的实现是一些代码行,因此我们通常为模型创建基类-例如实现了INotifyPropertyChanged的BaseModel或BaseViewModel.

No, they don't have to share anything. However the implementation of INotifyPropertyChanged is some lines of code, so we usually made a base class for models - like BaseModel or BaseViewModel which implemented INotifyPropertyChanged.

这些实现通常特定于您使用的C#语言版本(较旧的版本适用于较新的语言版本).

The implementations are generally specific to the version of C# language you use (the older ones works in the newer version of language).

查看此处: http://jesseliberty.com/2012/06/28/c-5making-inotifypropertychanged-easier/

但是您可以使它在基类中实现,而不是让Employee类实现INotifyPropertyChanged.

but instead of having the Employee class to implement the INotifyPropertyChanged, you can implement it in a base class

public class BaseViewModel : INotifyPropertyChanged
{

    public event PropertyChangedEventHandler PropertyChanged;
    protected void RaisePropertyChanged([CallerMemberName] string caller = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(caller));
        }
    }
}

,然后博客中的Employee类应该看起来像这样

and then the Employee class from the blog should look like this

public class Employee : BaseViewModel
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set
        {
            _name = value;
            RaisePropertyChanged();
        }
    }
}

这是针对C#5(.Net 4.5-在Windows XP上不运行的版本)

this is for C# 5 (the .Net 4.5 - the one which does not run on Windows XP)

这篇关于INotifyPropertyChanged用于模型和视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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