MVVM: How to handle interaction between nested ViewModels?

前端 未结 3 1910
悲&欢浪女
悲&欢浪女 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: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?

提交回复
热议问题