C#, WPF, MVVM and INotifyPropertyChanged

若如初见. 提交于 2019-11-30 13:45:43
Snowbear
  1. The problem is that you're raising PropertyChanged on your model, but your view is bound to ViewModel. So your View subscribes only to ViewModel events (not Model's) - that is why textbox is not updated - because it never receives PropertyChanged event. One of possible solutions is to listen in ViewModel for Model PropertyChanged events and raise same event on ViewModel accordingly.

  2. Initial value is being propagated because your setters/getters in ViewModel are correct, the problem is in events.

  3. Yes, you are correct (see my #1), you should raise PropertyChanged on your ViewModel because View is bound to it. These events will not be triggered automatically after changes in Model, so you should listen for Model.PropertyChanged in ViewModel.

Simplest dirty fix to understand the idea:

SimulatorViewModel(Simulator model)
{
    // this will re-raise Model's events on ViewModel
    // VM should implement INotifyPropertyChanged
    // method OnPropertyChanged should raise INPC for a given property
    model.PropertyChanged += (sender, args) => this.OnPropertyChanged(args.PropertyName);
}
  1. Always make sure that the instance of the class which has been set as Data-context should implement INotifyPropertyChanged
  2. In your case Simulator implements INotifyPropertyChanged but SimulatorViewModel is set as DataContext, in this case the UI will come to know only if there are changes in the SimulatorViewModel but not in the Simulator.

What you can do is that:

You can expose some events or delegates in the Simulator class and hook to some methods in SimulatorViewModel class. Then when ever values in Simulator class changes, invoke the event or the delegate that will get Execute on SimulatorViewModel, now you can get the updated values from the simulator and update the properties in SimulatorViewModel. Make sure that you use different properties in both the class

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