当MainWindow关闭时如何关闭所有窗口

6

我正在处理WPF技术。当应用程序启动时,会打开一个名为Mainwindow的窗口。此窗口中有两个按钮,每个按钮都会打开一个新窗口。例如,有添加和更新按钮。单击添加按钮会调用Add-Item窗口,并同样地,单击更新按钮会调用Update-Item窗口。 如果我关闭Mainwindow窗口,这两个窗口“Add-Item”和“Update-Item”将保持打开状态。我希望关闭Mainwindow窗口时,这两个窗口也能一起关闭。

app.current.shutdown

app.current.shutdown主要用于关闭应用程序。我的问题是:我应该在程序的哪个部分调用这个代码行,是在mainwindow还是在App.config中?需要在响应中调用任何事件或函数吗?

4个回答

13

您还可以在 App.xaml 文件中设置 ShutdownMode:

<Application x:Class="WpfApp1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WpfApp1"
    StartupUri="MainWindow.xaml"
    ShutdownMode="OnMainWindowClose">
    <Application.Resources>
    </Application.Resources>
</Application>

11

Application.MainWindow设置为您的主窗口实例,并确保Application.ShutdownModeOnMainWindowClose

另外,如果您不想让整个应用程序关闭:请将MainWindow设置为子窗口的Owner。(这会产生其他副作用)


这个要设置在哪里?@H.B - Zoya Sheikh
@ZoyaSheikh:其实无所谓,我会在App类的Application.OnStartup中完成它。(放弃StartupUri,手动创建窗口并分配它) - H.B.

4

0

由于乍一看很难弄清楚我们的朋友所建议的正确做法,因此我将采用一个小的示例(最佳实践)代码来进行说明。

这就是 Josh Smith 展示的您的 App.xaml.cs 应该是什么样子。

namespace MyApplication
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        static App()
        {
            // Ensure the current culture passed into bindings is the OS culture.
            // By default, WPF uses en-US as the culture, regardless of the system settings.
            //
            FrameworkElement.LanguageProperty.OverrideMetadata(
              typeof(FrameworkElement),
              new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var window = new MainWindow();

            // To ensure all the other Views of a type Window get closed properly.
            ShutdownMode = ShutdownMode.OnMainWindowClose;

            // Create the ViewModel which the main window binds.
            var viewModel = new MainWindowViewModel();

            // When the ViewModel asks to be closed,
            // close the window.
            EventHandler handler = null;
            handler = delegate
            {
                viewModel.RequestClose -= handler;
                window.Close();
            };
            viewModel.RequestClose += handler;

            // Allow all controls in the window to bind to the ViewModel by
            // setting the DataContext, which propagates down the element tree.
            window.DataContext = viewModel;
            window.Show();
        }
    }
}

再说,归根结底,如何布局你的MVVM应用程序取决于你自己。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接