wpf 从 Model 类通知 ViewModel 的属性更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17573263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:11:33  来源:igfitidea点击:

Notifying ViewModel of Property change from Model class

wpfxamltreeviewwpf-controls

提问by WAQ

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?

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

Thanks in advance.

提前致谢。

回答by New Dev

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.

我猜你的模型实例是你的 ViewModel 的一部分......首先,它应该实现 INotifyPropertyChanged。如果您还希望您的 ViewModel 得到通知,那么您的 ViewModel 应该订阅该事件。

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