How to have multiple pairs “View-ViewModel”?

前端 未结 3 1561
伪装坚强ぢ
伪装坚强ぢ 2020-12-03 15:22

I am building an application that is based on MVVM-Light. I am in the need of creating multiple instances of the same View, and each one should bind to its own ViewModel.

相关标签:
3条回答
  • 2020-12-03 15:38

    There is no obligation to store the ViewModels as singletons in the ViewModelLocator, but it certainly makes them easier to find if the view is a singleton too. Obviously, if you have multiple instances of the same View class, you will have multiple instances of the same ViewModel class, and it cannot be a singleton anymore.

    To keep track of the multiple instances of the ViewModel, you can implement a dictionary in the ViewModelLocator that looks up for a ViewModel according to a key. The key can be a unique ID for the view, for example. Once you get hold of the view, retrieve its key and then retrieve the viewmodel from the locator.

    Update: Often you don't even need to track multiple viewmodels. For instance, you can have the Messenger class send a message to all instances of a given viewmodel class using the Send overload. So before implementing a dictionary to keep track of the VMs, ask yourself if you really need it! ;)

    Hope that helps, Laurent

    0 讨论(0)
  • 2020-12-03 15:42

    I used the naming system of the unity container.

    See "How to distinguish multiple view/view model pairs using unity container".

    0 讨论(0)
  • 2020-12-03 15:47

    I had a problem posted and solved in this SO question. It turned out to be very much related to Mr Bugnion's answer here (which helped me tremendously, thank you!)

    What I've found is you don't need to store the view-model property in ViewModelLocator at all. Just use ServiceLocator to create an instance with a key, and in your "Dialog Service", pass the key to ShowDialog<T>(string key = null).

    Also, as mentioned in this thread already, use method Messenger.Default.Send and remember to call viewModel.Cleanup() afterwards to unregister the view-model from Messenger, thereby preventing phantom view-models from trying to process future messages sent to all instances of the view-model class type.

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