简体   繁体   English

在没有用户交互的情况下关闭 WPF 对话框

[英]Close WPF dialog without user interaction

I would like to show dialog during some IO operations and after it, close the dialog with code.我想在某些 IO 操作期间显示对话框,然后用代码关闭对话框。 Something like:类似的东西:

DialogWindow dialog = new DialogWindow();
dialog.ShowDialog();
.... do some file operation....
dialog.Close();

but dialog won't close.但对话框不会关闭。 I have to close it by myself.我必须自己关闭它。 Is here way how to close it with code?这里是如何用代码关闭它的方法吗?

Try to use .Show(), not ShowDialog().尝试使用 .Show(),而不是 ShowDialog()。 If you use ShowDialog, the new window is modal, so you must close manually the window, before you can reach the line of codice dialog.Close().如果您使用 ShowDialog,新窗口是模态的,因此您必须手动关闭窗口,然后才能到达 codice dialog.Close() 行。

You can not use ShowDialog() because it blocks the current thread.您不能使用 ShowDialog(),因为它会阻塞当前线程。

You could disable the owner window while the process is running and then enable it afterwards like this ('this' is the owner window) (you'll have to be carefull with errors and exceptions, of course):您可以在进程运行时禁用所有者窗口,然后像这样启用它('this'是所有者窗口)(当然,您必须小心错误和异常):

    async private void Button_Click(object sender, RoutedEventArgs e)
{
  Window1 win = new Window1();
  this.IsEnabled = false;
  win.Show();
  await Task.Run(() =>
    {
      Thread.Sleep(2000);
    });

  win.Close();
  this.IsEnabled = true;
}

An alternative is to run the file operation in the opened dialog (opened with ShowDialog() then) instead of in the main window.另一种方法是在打开的对话框(然后用 ShowDialog() 打开)而不是在主窗口中运行文件操作。

If using ShowDialog() then can use below code to close dialog.如果使用 ShowDialog() 那么可以使用下面的代码来关闭对话框。

(this.Parent as Window).Close(); (this.Parent 作为 Window).Close();

DialogWindow dialog = new DialogWindow();
Task.Run(()=>
{
    .... do some file operation....
    Dispatcher.BeginInvoke((Action)dialog.Close);
});
dialog.ShowDialog();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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