How do I update the parent viewmodel when child viewmodel is updated

前端 未结 1 647
刺人心
刺人心 2020-12-18 14:54

In my first view model (renamed to MainViewModel) I have a list of ActionViewModels. In my xaml i have a listbox which is bound to the list, in the listbox i have a template

相关标签:
1条回答
  • 2020-12-18 15:05

    There are 3 ways I can think of that would allow you to do this.

    1. The ActionService could send out some sort of notification when data changes. One easy way to do this is to use the MvvmCross Messenger plugin. This is the way the CollectABull service works in CollectionService.cs in the N+1 days of mvvmcross videos (for more info watch N=13 in http://mvvmcross.wordpress.com)

      This is the approach I generally use. It has low overhead, uses WeakReferences (so doesn't leak memory), it is easily extensible (any object can listen for changes), and it encourages loose coupling of the ViewModel and Model objects

    2. You could implement some kind of Refresh API on the list ViewModel and could call this from appropriate View events (e.g. ViewDidAppear, OnNavigatedTo and OnResume).

      I don't generally use this approach for Refreshing known data, but I have used it for enabling/disabling resource intensive objects - e.g. timers

      For certain shape of model data (and especially how often it changes), then I can imagine scenarios where this approach might be more efficient than the messenger approach.

    3. You could extend the use of INotifyPropertyChanged and INotifyCollectionChanged back into your model layer.

      I've done this a few times and it's worked well for me.

      If you do choose this approach, be careful to ensure that all Views do subscribe to change events using WeakReference subscriptions such as those used in MvvmCross binding - see WeakSubscription. If you didn't do this, then it could be possible for the Model to cause Views to persist in memory even after the UI itself has removed them.

    0 讨论(0)
提交回复
热议问题