this.Close(); 在窗口 wpf 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33823326/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:33:07  来源:igfitidea点击:

this.Close(); doesn't work in window wpf

c#wpf

提问by Rashmi S

In wpf, window I am calling window forms. Before calling that I just want to close that window. Here is my code.

在 wpf 中,我正在调用窗口窗体。在调用之前,我只想关闭该窗口。这是我的代码。

  public partial class MainWindow : MetroWindow
  {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void BtnIntroClick(object sender, RoutedEventArgs e)
        {

            PdfReader form = new PdfReader(1);

            form.ShowDialog();
            this.Close();

        }
   }

No error, but form is not closing. And in window form also, this.Close()in not working

没有错误,但表单没有关闭。并且在窗口形式中,也this.Close()无法正常工作

 public partial class PdfReader : Form
 {
        public PdfReader(int page_num)
        {
            InitializeComponent();
            var executingFolder = System.AppDomain.CurrentDomain.BaseDirectory;
            var dbPath = System.IO.Path.Combine(executingFolder, "BiodermaProduct.pdf");
            axAcroPDF1.LoadFile(dbPath);

            axAcroPDF1.setCurrentPage(page_num);
        }

        private void PdfReader_FormClosed(object sender, FormClosedEventArgs e)
        {
           this.Opacity = 0;
           MainWindow w = new MainWindow();
           w.ShowDialog();

        }
 }

回答by Winger Sendon

It will close when you close your PdfReader form. Form.ShowDialogreturns only when the form is closed. So this.Close()is not called until ShowDialogfinishes.
What you can do is set this.Visibility = Visibility.Hiddenbefore calling form.ShowDialog();

当您关闭PdfReader form. Form.ShowDialog仅在表单关闭时返回。所以this.Close()ShowDialog完成之前不会被调用。
你可以做的是this.Visibility = Visibility.Hidden在调用之前设置form.ShowDialog();

回答by Mr.B

Important detail that we need to bear in mind when we deal with windows closure and other UI operation: we need to execute it in UI thread only. This is exactly that happened in my case.

我们在处理windows关闭和其他UI操作时需要记住的重要细节:我们只需要在UI线程中执行它。这正是在我的情况下发生的。

I raised an event from the server and when it happened I raised another event through custom Event Aggregatorto close the second Window that is opened (without shutting down the application). However it didn't happen without an error or visible reason. My window was still opened. Nevertheless, when I enabled "Common Language Runtime exception" through visual studio settings:

我从服务器引发了一个事件,当它发生时,我通过自定义事件聚合器引发了另一个事件以关闭打开的第二个窗口(不关闭应用程序)。然而,它并不是没有错误或明显的原因就发生的。我的窗户还开着。尽管如此,当我通过 Visual Studio 设置启用“公共语言运行时异常”时:

enter image description here

在此处输入图片说明

I caught the exception: "Full Exception: System.InvalidOperationException: The calling thread cannot access this object because a different thread owns it. at System.Windows.Threading.Dispatcher.VerifyAccess() at System.Windows.Window.Close().........."

我发现了异常:“完整异常:System.InvalidOperationException:调用线程无法访问此对象,因为另一个线程拥有它。在 System.Windows.Threading.Dispatcher.VerifyAccess() 在 System.Windows.Window.Close()。 …………

Consequently, instead of this:

因此,而不是这样:

  ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ServerDisconnectedEvent>()
         .Subscribe(e => Close());

Run this:

运行这个:

        ServiceLocator.Current.GetInstance<IEventAggregator>().GetEvent<ServerDisconnectedEvent>()
            .Subscribe(e => Application.Current.Dispatcher.BeginInvoke(new Action(Close)));

I hope this will safe time for someone like me :)

我希望这对像我这样的人来说是安全的时间:)

回答by Ryan Amies

If you read this MSDN articleyou'll see that ShowDialogonly returns when said window is closed. This means your code is blocked on that line until the window is closed. You have to close your current window first, then ShowDialog.

如果您阅读这篇 MSDN 文章,您会看到ShowDialog只有在所述窗口关闭时才会返回。这意味着您的代码在该行被阻止,直到窗口关闭。您必须先关闭当前窗口,然后ShowDialog

    private void BtnIntroClick(object sender, RoutedEventArgs e)
    {
        PdfReader form = new PdfReader(1);
        this.Close();
        form.ShowDialog();

    }

Note that Showdoes not work in this way.

请注意,Show这种方式不起作用。

回答by StepUp

When You use Window.ShowDialog(), it calls new Window modally, meaning you cannot go to the parent form.

当您使用 时Window.ShowDialog(),它会以模态方式调用 new Window,这意味着您无法转到父窗体。

The Window.Show()function shows the form in a non modal form. This means that you can click on the parent form.

Window.Show()函数以非模态形式显示表单。这意味着您可以单击父窗体。

However, this code will close your application as MSDN says(thanks to @Empereur Aiman):

但是,正如MSDN 所说,此代码将关闭您的应用程序(感谢@Empereur Aiman):

A ShutdownMode of OnMainWindowClose causes Windows Presentation Foundation (WPF) to implicitly call Shutdown when the MainWindow closes, even if other windows are currently open.

OnMainWindowClose 的 ShutdownMode 会导致 Windows Presentation Foundation (WPF) 在 MainWindow 关闭时隐式调用 Shutdown,即使其他窗口当前处于打开状态

And you should set your ShutdownModeto OnLastWindowCloseas MSDN says:

你应该设置你ShutdownModeOnLastWindowCloseMSDN说

If you set ShutdownMode to OnLastWindowClose, Windows Presentation Foundation (WPF) implicitly calls Shutdown when the last window in an application closes, even if any currently instantiated windows are set as the main window (see MainWindow).

如果将 ShutdownMode 设置为 OnLastWindowClose,Windows Presentation Foundation (WPF) 在应用程序中的最后一个窗口关闭时隐式调用 Shutdown,即使任何当前实例化的窗口被设置为主窗口(请参阅 MainWindow)。

Just reorder your call of ShowDialog():

只需重新排序 ShowDialog() 的调用:

PdfReader form = new PdfReader(1);
this.Close();
form.ShowDialog();

or:

或者:

PdfReader form = new PdfReader(1);
form.Show();
this.Close();

and set ShutdownMode="OnLastWindowClose"at App.xamlfile of your application:

ShutdownMode="OnLastWindowClose"App.xaml您的应用程序文件中设置:

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="MainWindow.xaml"
    ShutdownMode="OnLastWindowClose"
    >
</Application>

You code is:

你的代码是:

PdfReader form = new PdfReader(1);
form.ShowDialog();
this.Close();

It means CLRexecutes modallyyour new PdfReaderwindow. That is, execution of your program goes to PdfReaderwindow. And only after closingPdfReader window, CLRexecutes your next row:

这意味着CLR模态方式执行您的新PdfReader窗口。也就是说,程序的执行转到PdfReader窗口。只有在关闭PdfReader 窗口后,才CLR执行下一行:

this.Close();

and your MainWindow()will be closed.

你的MainWindow()遗嘱将被关闭。

回答by Hazem Abdullah

You need to change the order between this.Close();& form.ShowDialog();and it will work well

您需要更改this.Close();&之间的顺序form.ShowDialog();,它会运行良好

Try this code:

试试这个代码:

private void BtnIntroClick(object sender, RoutedEventArgs e)
{

  PdfReader form = new PdfReader(1);
  this.Close();
  form.ShowDialog();
 }