MVVM: How to handle interaction between nested ViewModels?

前端 未结 3 1901
悲&欢浪女
悲&欢浪女 2021-02-02 13:26

I\'m been experimenting with the oft-mentioned MVVM pattern and I\'ve been having a hard time defining clear boundaries in some cases. In my application, I have a dialog that a

相关标签:
3条回答
  • 2021-02-02 13:41

    I recently experimented with Unity (Microsoft Enterprise library) to use dependency injection. That might be a route to go when using interfaces that completely define what both viewmodels need to no from each other. MEF would be another option for dependency injection I'm aware of.

    HTH

    0 讨论(0)
  • 2021-02-02 13:46

    I think you want to make your top-level ViewModel aware of the existence of the NestedViewModel, it makes sense from a hierarchical standpoint, the master view contains the child view.

    In my opinion, your instinct is right, it doesn't feel correct for the nested ViewModel to expose behaviours which are initiated by user actions on the top-level. Instead, the top-level ViewModel should be providing behaviors for the view it is associated with.

    But I'd consider moving responsibility for connection construction into an ICommand, and exposing this command via your top-level ViewModel. The OK button on your master dialog you would then bind to this command, and the command would just delegate to the top-level ViewModel, for example, call ViewModel.CreateConnection() when it is executed.

    The responsibility of your nested control is then purely collecting and exposing the data to its NestedViewModel, for consumption by the containing ViewModel, and it is theoretically more re-usable in different contexts that require the same information to be entered (if any) - let's say you wanted to re-use it for editing already-created connections.

    The only wrinkle would be if the different types of NestedViewModel expose a radically different set of data.

    For example, one exposes HostName and Port as properties, and another exposes UserName and Password.

    In which case you may need to do some infrastructural work to have your top-level ViewModel.CreateConnection() still work in a clean manner. Although if you have a small amount of nested control types, it may not be worth the effort, and a simple NestedViewModel type-check and cast may suffice.

    Does this sound viable?

    0 讨论(0)
  • 2021-02-02 13:47

    An option which works well for interaction between viewmodels is to bind directly to observer classes sitting between the viewmodel classes.

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