Notifying ViewModel of Property change from Model class

非 Y 不嫁゛ 提交于 2020-01-21 13:39:05

问题


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?

Thanks in advance.


回答1:


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


来源:https://stackoverflow.com/questions/17573263/notifying-viewmodel-of-property-change-from-model-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!