从 Model 类通知 ViewModel 的属性更改 [英] Notifying ViewModel of Property change from Model class

查看:39
本文介绍了从 Model 类通知 ViewModel 的属性更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 WPF 应用程序中,我将 TreeView IsSelected 属性绑定到我的 Model 类中的一个属性.所以选中的Item是在Model类中设置的.每当设置/更改所选项目时,我都需要通知我的 ViewModel.我该怎么做?

In my WPF application, I have my TreeView IsSelected property binded to a property in my Model class. So the selected Item is set in the Model class. I need to notify my ViewModel whenever the selected Item is set/changed. How can I do that?

提前致谢.

推荐答案

我猜你的 Model 实例是你的 ViewModel 的一部分...首先,它应该实现 INotifyPropertyChanged.如果您还希望 ViewModel 收到通知,则您的 ViewModel 应该订阅该事件.

I guess your Model instance is part of your ViewModel... First, yes it should implement INotifyPropertyChanged. If you also want your ViewModel to get notified, then you ViewModel should subscribe to that event.

public class Model : INotifyPropertyChanged
{
   private string _name;
   public string Name {
      get {return _name;}
      set {
         _name = value;
         NotifyPropertyChanged("Name");
   }
// etc... including INPC implementation
}

public class ViewModel : INotifyPropertyChanged {
   public ViewModel (Model model){
      this.MyModel = model;
      this.MyModel.PropertyChanged += (s,e) => { DoSomething();};
   }

   public Model MyModel { get; set; }
}

这篇关于从 Model 类通知 ViewModel 的属性更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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