views:

105

answers:

2

I created a WPF Window and made it a MEF Export.

I can do a ShowDialog once on the MEF Import but the second time it aborts because the MEF component was closed by the first ShowDialog.

What can be done to allow repeats of ShowDialog?

+2  A: 

When you call ShowDialog on a WPF window twice like this:

var window = new Window();
window.ShowDialog(); // returns when user closes first window
window.ShowDialog(); // throws 

you will get an InvalidOperationException with this message:

Cannot set Visibility or call Show or ShowDialog after window has closed.

To fix this, you need to recreate the window each time, e.g. like this:

var window = new Window();
window.ShowDialog();
window = new Window();
window.ShowDialog();

To do this in MEF, you could export a separate controller component which is responsible for creating and then showing your dialog (rather than exporting your dialog directly):

[Export]
public class MyDialogController
{
   public void ShowMyDialog()
   {
      using (var myDialog = new MyDialog())
      {
          myDialog.ShowDialog();
      }
   }
}
Wim Coenen
Well done Wim Coenen, well done. It should work for my situation.
BSalita
A: 

Further examples on how to use MEF within a WPF application can be found in the WPF Application Framework (WAF) project download (have a look at the sample applications).

jbe