C# WPF 窗口关闭事件用法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10033551/
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
WPF Window Closed Event Usage
提问by Ternary
I have a Windowclass (e.g. public partial class Foo : Window), and when I create the window I sign up for the Closedevent as such.
我有一个Window类(例如public partial class Foo : Window),当我创建窗口时,我注册了该Closed事件。
foo = new Foo();
foo.Closed += FooClosed;
public void FooClosed(object sender, System.EventArgs e)
{
}
When someone presses a button inside the fooWindow I call this.Close()but my FooCloseddoesn't seem to be called.
当有人按下foo窗口内的按钮时,我会调用this.Close()但我的FooClosed似乎没有被调用。
Am I incorrectly signing up for the event?
我是否错误地注册了该活动?
Update
更新
By the way, all I'm trying to accomplish is knowwhen foohas been closed so I can set the reference back to null. Is there a better way to accomplish that?
顺便说一句,我想要完成的只是知道何时foo关闭,以便我可以将引用设置回null. 有没有更好的方法来实现这一点?
回答by Dan P
Question was answered a few days ago check Execute code when a WPF closes
几天前回答了问题检查WPF 关闭时执行代码
You may have something going on with your code because this works just fine for me.
您的代码可能有问题,因为这对我来说很好用。
MainWindow.xaml.cs
主窗口.xaml.cs
namespace WpfApplication1
{
public partial class MainWindow : Window
{
private Foo foo;
public MainWindow()
{
InitializeComponent();
foo = new Foo();
foo.Closed += FooClosed;
foo.Show();
}
public void FooClosed(object sender, System.EventArgs e)
{
//This gets fired off
foo = null;
}
}
}
Foo.xaml
文件.xaml
<Window x:Class="WpfApplication1.Foo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Foo" Height="300" Width="300">
<Grid>
<Button Click="Button_Click">Close</Button>
</Grid>
</Window>
Foo.xaml.cs
文件.xaml.cs
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Foo.xaml
/// </summary>
public partial class Foo : Window
{
public Foo()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}

