With MVVM and WPF what would be a good/straightforward way to handle opening and closing new windows and dialogs? Opening and closing should be driven by the ViewModel right? But the ViewModel should not know about the view ...
Asked
Active
Viewed 3,622 times
1 Answers
6
I usually use interfaces for this. For example, if i want to edit a record in a separate window, i have an interface IEditingProvider<TViewModel>, which i can implement somewhere else and then pass an interface reference to the constructor of my ViewModel. The EditingProvider might just do something like this:
class MyRecordEditingProvider: IEditingProvider<MyRecordViewModel>
{
// Implementation of generic interface method
public void Edit(MyRecordViewModel model) {
EditWindow edit = new EditWindow();
edit.DataContext = model;
edit.ShowDialog();
}
}

Botz3000
- 39,020
- 8
- 103
- 127
-
How an where do you maintain the EditingProviders that are available to (a certain part of) your application and how do you retrieve the correct instance that you eventually will pass to the ViewModel's constructor? I suppose it is not all hardwired but decoupled? – bitbonk Sep 23 '09 at 11:09
-
Yes, it is decoupled. Actually i'm using a Dependency Injection Framework (Composite Application Block by Microsoft) for mapping the generic interfaces to implementations. I am currently doing that in code, but the Unity Container can also be configured using a configuration file. – Botz3000 Sep 23 '09 at 19:48
-
Do you have a MVVM-friendly solution to set the `Owner` property of your EditWindow before you call ShowDialog? If the Owner is not set (to the MainWindow, for example) the modal dialog can go behind the main window which is quite weird and confusing from user perspective. – Slauma Mar 01 '11 at 18:52
-
1That's a good question. Last time i had that problem, i just determined the currently active window and set that one as the parent. You could do that for example by looking through Application.Current.Windows and see which one has IsActive set to true. I think i did that in the Window constructor. I'm not sure anymore though. – Botz3000 Mar 02 '11 at 18:24
-
That's good! I just tried this out and it seems to work. Good that I asked - I was already thinking about passing `Window` instances into my ViewModels and moving them around just to get the owner finally into my Dialog service where I create the dialogs. Your's is a much easier solution. Thank you very much for this tip! – Slauma Mar 02 '11 at 22:28