c# - 如何检查 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;
}
解决方案
您可以使用Application.Current.Windows.OfType().FirstOrDefault()在运行时获取第二个窗口,然后您可以检查它是否打开。我将在我的演示中向您展示详细步骤:
MainWindow.xaml 的代码(作为第一页):
<StackPanel>
<TextBlock Text="This is the first Window" FontSize="30"></TextBlock>
<Button Content="Open Child Window:" 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>
推荐阅读
- java - [hashmap][iterator] 给出一半值
- python - 如何引用熊猫系列中的前/后值?
- php - 致命错误:找不到类“Carbon_Fields\Widget”
- matplotlib - python3.6 无法导入 tkinter & 在哪里为 python3.6 安装 tkinker
- ios - AV Foundation 和 VideoToolboox 有什么区别?
- tensorflow - 如何在张量流中随机初始化权重?
- scala - 将值写入不同的文本文件以获取不同的键 scala
- node.js - 需要在 Node.js 中指定 HTTP 请求元素的顺序
- ruby-on-rails - 如何将我的网址更改为帖子链接 ID?
- database - python中的远程Oracle DB连接