WPF MVVM 关闭窗口 [英] WPF MVVM Close Window

查看:116
本文介绍了WPF MVVM 关闭窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 MVVM 创建了一个 WPF 应用程序,但在关闭/打开窗口时遇到了困难.在我的登录窗口中,我使用以下方法关闭登录窗口并单击按钮打开 WindowOPHome 窗口:

I have created a WPF App using MVVM and I'm having difficulty with closing/opening windows. On my Login Window, I use the following method to close the Login Window and Open the WindowOPHome Window with a button click:

            WindowOPHome dashboard = new WindowOPHome();
            dashboard.Show();
            Application.Current.MainWindow.Close();

一切正常,登录窗口关闭,同时 WindowOPHome 窗口打开.当我尝试关闭 WindowOPHome 窗口并通过单击类似于登录窗口/WindowOPHome 操作的按钮打开 WindowMainAdmin 窗口时,WindowMainAdmin 窗口打开一瞬间然后消失,而 WindowOPHome 永远不会离开视线.以下是关闭 WindowOPHome 和打开 WindowMainAdmin 的代码:

Everything works fine and the Login Window closes while the WindowOPHome Window opens. When I try to close the WindowOPHome Window and open the WindowMainAdmin Window with a button click similar to the Login Window/WindowOPHome action, the WindowMainAdmin Window opens for a split second then disappears while the WindowOPHome never leaves sight. Following is code for closing WindowOPHome and opening WindowMainAdmin:

        WindowMainAdmin dashboard = new WindowMainAdmin();
        dashboard.Show();
        Application.Current.MainWindow.Close();

任何帮助将不胜感激!如果您需要任何其他代码,请告诉我.非常感谢!

Any help would be greatly appreciated! Please let me know if there any other pieces of code you need. Thank you so much!

推荐答案

我建议您明确关闭要关闭的窗口,而不是假设它是当前主窗口.

I'd suggest you explicitly close the window you want to close rather than assuming it's the current main window.

使用 MVVM 有很多不同的方法可以做到这一点,您可以使用附加行为或通过命令参数将窗口传递给视图模型,如下所示:

With MVVM there are lots of different ways to do it, you can use an attached behavior or pass the window to the view model via the command parameter like this:

在视图的按钮 xaml 中:

in the button xaml for the view:

CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}"

在视图模型中的命令execute方法中:

in the command execute method in the view model:

if (parameter is System.Windows.Window)
{
    WindowMainAdmin dashboard = new WindowMainAdmin();
    dashboard.Show();
    (parameter as System.Windows.Window).Close();
}

.
或者,您可以迭代所有窗口,直到找到所需的窗口.

.
Alternatively, you could iterate all windows until you find the one you want.

foreach( Window window in Application.Current.Windows ) {
    if(window is WindowOPHome)
    {
        window.Close();
        break;
    }  
}

如果您需要打开多个窗口实例,除了关闭该类型的第一个属性外,您可能还需要检查其他一些属性.

You might want to check on some other property other than just closing the first one of that type if you need to have more than one instance of a window open.

您甚至可以将其调整为每个窗口类中的静态关闭方法.

You could even adapt that to be a static close method within each window class.

这篇关于WPF MVVM 关闭窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆