WPF MVVM communication between View Model

前端 未结 3 1334
别那么骄傲
别那么骄傲 2020-12-08 08:53

I am working on WPF MVVM application wherein I have 2 views View1 and View2 with their respective ViewModels. Now, I want on click of a button in View1 would close View1 and

3条回答
  •  死守一世寂寞
    2020-12-08 09:08

    How about using the Mediator pattern (for example see technical-recipes.com or John Smith) or weak events? Afaik several MVVM frameworks/libs (like PRISM, Caliburn.Micro, MVVMCross) already come with the infrastructure code for these. There are also separate libraries that are independent of any specific MVVM framework, like Appccelerate EventBroker which can help you achieve something along the lines of what you want.

    With events, however, I wonder whether you require some feedback on whether the event was "correctly" handled or not. There are ways to achieve this (altering the value of the event args, handling the events sync, after raising the event, checking the value of the event args), but they are not as concise as a method's return value or a method throwing an exception.

    EDIT: sorry I just realized that the second view/ViewModel is not open, yet. So my "solution" is not (that simply) applicable. You need to pass the instruction "up" in the view model tree, maybe even to the root, where you can instantiate and show the new view model (show in a new window or as a ContentControl in an existing view?)

提交回复
热议问题