C# – WPF MVVM Get Parent from VIEW MODEL

cmvvmmvvm-lightnetwpf

In a MVVM WPF application.

How do you set a second windows parent from the ViewModel?

example:

view1viewModel1

viewModel1's command calls:

var view2 = new view2

view2.Owner = <—-This is the problem area. How do I get view1 as the owner here from the viewModel?

view2.Show()

EDIT:

See accepted answer below, then read the following edit.

I'am using MVVM light -> http://mvvmlight.codeplex.com/ (awesome btw)

The baked-in messaging system is great. I am now sending a message from the viewmodel to my view telling it to show another window.

For the message I'am currently using a string with a switch statement in the main view to determine what view to open; however I may tinker with the tokens that also are part of MVVM light toolkit.

Thank you!

Best Answer

In my opinion, opening a new window is the responsibility of the View, not of the ViewModel. Personally, I would use the same approach as used for displaying a dialog box (this was discussed in this forum already):

Have the ViewModel send a Message to the View requesting that it opens a new Window. (alternatively) use an IDialogService or whatever you want to call it which you pass to the ViewModel's constructor. This service will be in charge of opening the Window (or of delegating this task to the View). This way, you keep a clean separation of concerns and your VM remains testable (you can unit test that the request to open the new WIndow has been sent, but you couldn't test that the window has been, indeed, open).

Does that make sense?

Cheers,

Laurent

Related Topic