2

I have a parent view which shows a grid. In one of the columns there is a button on every row to show a child dialog to edit the object that each row of the grid is bound to. The button is bound to a command on the view model which shows the dialog. I use CommandParameter="{Binding}" to pass a reference to object to edit to the view model of the child dialog.

I want to the dialog to be centered relative to the window it opened from which I can do with dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner but I need a reference to the parent window.

I can think of two solutions but I don't think either of them is clean.

  1. If I wasn't using the command parameter already I could pass the window to parent view model like this CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}". I could use a multi binding and a converter to pass two parameters but is this good practice? I tend to think the view model shouldn't know any thing about views.

  2. I can pass a reference to the parent window that host the parent view to it's view model in the view model's constructor. Again what I don't like is that the view model knows about windows which seems like a dependency in the wrong direction.

What I also don't like about either of these approaches is the parent view model needs to have knowledge of the child window it is creating.

I sawthis answer which shows how to use a service that the view model can use to open a window without having any knowledge of the window its creating which is great but I kind think of a clean way to pass the parent window without going through the view model.

Shane
  • 2,271
  • 3
  • 27
  • 55
  • Sometime I just access the parent main window like this : 'var mainWindow=System.Windows.Application.Current.MainWindow;' – Dark Knight Sep 18 '18 at 10:22
  • This can be helpful for you [Q: Is MVVM pattern broken?](https://stackoverflow.com/q/42931775/7713750). See also [A: Open File Dialog MVVM](https://stackoverflow.com/a/43756154/7713750) – Rekshino Sep 18 '18 at 10:35
  • You could use `Popup` instead of a seperate dialog as it is easier to control from a 'parent' and centers on the parent by default. – Steffen Winkler Sep 18 '18 at 13:12

0 Answers0