首页 > 解决方案 > 如何检查 WPF 窗口是否从另一个 WPF 窗口关闭?

问题描述

我是 WPF 环境的新手,我想知道如何处理 Window_closed 事件,我的意思是如何从另一个 Window 窗体检查窗口是否已关闭,我刚刚编写了一些代码:

 // Window form 1
           
            for (int k = 0; k <= listgrid.Count - 1; k++)
            {
                test  test = new test(listgrid[0]); // the new form ( Window form 2 )
                test.Show();
                if (test.IsClosed) // I need to check here if the window form 2 is closed or not
                {
                    Console.WriteLine("OKK Is closed after  " + test.IsClosed);
                    test.Show();
                }

            }


// Second form
  public partial class test : Window
    {
        public bool test_close;

        public test(GridModel gridModel)
        {
            InitializeComponent();           
 
        }

        private void Window_Closed(object sender, EventArgs e)
        {
        //      base.Close();
            IsClosed = true;
            Console.WriteLine( " Ok " +IsClosed);
        }
        public bool IsClosed { get; private set; }

        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            IsClosed = true;
        }

标签: c#wpfvisual-studio

解决方案


您可以使用Application.Current.Windows.OfType().FirstOrDefault()在运行时获取第二个窗口,然后您可以检查它是否打开。我将在我的演示中向您展示详细步骤:

MainWindow.xaml 的代码(作为第一页):

 <StackPanel>
    <TextBlock Text="This is the first Window" FontSize="30"></TextBlock>
    <Button Content="Open Child Window:&quot; FontSize="15" HorizontalAlignment="Left" VerticalAlignment="Top" Width="287" Height="39" RenderTransformOrigin="0.5,0.5" Click="OpenButton_Click" />
    <Button Content="Check child " Width="287" Height="39" Click="Button_Click" VerticalAlignment="Center"  HorizontalAlignment="Left"/>
</StackPanel>

ainWindow.xaml.cs 的代码:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        var oldWindow = Application.Current.Windows.OfType<SecondWindow>().FirstOrDefault();
        if (oldWindow != null)
        {
            MessageBox.Show("The Child_Window is open!");
        }else
        {
            MessageBox.Show("The Child_Window is closed");

        }
    }

    private void OpenButton_Click(object sender, RoutedEventArgs e)
    {
        SecondWindow newWindow = new SecondWindow();
        newWindow.Show();
    }

SecondWindow.xaml 的代码更简单,只有一行代码:

<Grid>
    <TextBlock Text="This is second Window!" FontSize="30"></TextBlock>
</Grid>

运行项目时,可以得到以下结果: 在此处输入图像描述


推荐阅读