简体   繁体   中英

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

有关如何在WPF应用程序中使用MEF的更多示例可以在WPF应用程序框架(WAF)项目下载中找到(请查看示例应用程序)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM