WPF MVVM Get Parent from VIEW MODEL

May 3, 2010 at 11:03 PM

I am having an interesting time getting this to work:

Has anyone used the messaging system in mvvm light toolkit to get this working, or some other method?

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

example:

view1 viewModel1

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()

Thank you!

Coordinator
May 3, 2010 at 11:51 PM

Hi,

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

PS: For more responses, I recommend you post questions to http://stackoverflow.com/questions/tagged/mvvm-light (make sure to use the tag mvvm-light). I check the questions as often as I can, and more qualified people lurk there and are able to answer your questions if I can't ;)

May 3, 2010 at 11:59 PM

Laurent - thank you for the response.

Currently I'am using an interface that is passed into the viewmodels constructor, the part I was missing is sending a message to the view to open a new view / dialog etc... 

This makes sense as it will be able to handle assigning ownership etc... I am going to give it a try and post the results on stackoverflow - I created this post and tagged with mvvm-light:

http://stackoverflow.com/questions/2761162/wpf-mvvm-get-parent-from-view-model

Once again thank you for your valuable time!