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.
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.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.