我不熟悉如何使用事件处理程序,想问一下是否有人能提供或指导我如何使用一个事件处理程序,在关闭/已关闭事件上执行代码?
我知道这是可行的,因为有一个已回答的问题:
但我需要一些指引。
谢谢 =)
我不熟悉如何使用事件处理程序,想问一下是否有人能提供或指导我如何使用一个事件处理程序,在关闭/已关闭事件上执行代码?
我知道这是可行的,因为有一个已回答的问题:
但我需要一些指引。
谢谢 =)
就是这个 XAML
<Window ... Closing="Window_Closing" Closed="Window_Closed">
...
</Window>
并编写用于 Closing
和 Closed
事件的代码
private void Window_Closing(object sender, CancelEventArgs e)
{
...
}
private void Window_Closed(object sender, EventArgs e)
{
....
}
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Closed += new EventHandler(MainWindow_Closed);
}
void MainWindow_Closed(object sender, EventArgs e)
{
//Put your close code here
}
}
}
如果你想在XAML和代码后台中都进行某些部分,请在XAML中进行如下操作:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" Closed="MainWindow_Closed">
<Grid>
</Grid>
</Window>
并且这是在.cs文件中
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
void MainWindow_Closed(object sender, EventArgs e)
{
//Put your close code here
}
}
}
上面两个示例可以应用于 XAML 应用程序中的任何窗体。您可以拥有多个窗体。如果您想为整个应用程序的退出过程应用代码,则修改您的 app.xaml.cs 文件以实现此目的。
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
try
{
//Put your special code here
}
finally
{
base.OnExit(e);
}
}
}
}
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
protected override void OnExit(ExitEventArgs e)
{
//do your things
base.OnExit(e);
}
}
protected override
来声明方法,则智能感知会启动。 - FrankMusing System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Name_Space
{
public partial class Window : Form
{
public Window()
{
InitializeComponent();
//...
}
private void Window_Load(object sender, EventArgs e)
{
//...
}
private void Window_Closed(object sender, EventArgs e)
{
// Your code goes here...!
}
}
}
...
private void InitializeComponent()
{
...
//
// Window
//
...
this.Closed += new System.EventHandler(this.Window_Closed); // <-- add this line
}
...
OnExit
代替OnStartup
。http://manaspatnaik.com/blog/index.php/technology/wpf/event-handling-in-wpf/193 - N_A