开发者

ShowDialog on MEF Component Only Works Once

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 M开发者_Go百科EF component was closed by the first ShowDialog.

What can be done to allow repeats of ShowDialog?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜