C# 阻止窗户关闭的最佳方法?
我正在寻找在我的软件中拦截关闭窗口的最佳方法。例如,我想截取一个名为“settings”的表单的闭包,而不是主窗口。vb.net的过程非常简单,我只需调用它的关闭事件,但使用WPF,我无法理解为什么没有捕获此事件,因此,内部代码没有执行。以您希望截取关闭事件的形式:C# 阻止窗户关闭的最佳方法?,c#,wpf,C#,Wpf,我正在寻找在我的软件中拦截关闭窗口的最佳方法。例如,我想截取一个名为“settings”的表单的闭包,而不是主窗口。vb.net的过程非常简单,我只需调用它的关闭事件,但使用WPF,我无法理解为什么没有捕获此事件,因此,内部代码没有执行。以您希望截取关闭事件的形式: protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if(dontClose) {
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if(dontClose)
{
e.Cancel = true;
}
base.OnClosing(e);
}
将dontClose替换为不关闭的条件。以您要拦截关闭的形式:
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if(dontClose)
{
e.Cancel = true;
}
base.OnClosing(e);
}
将dontClose替换为不关闭的条件。在XAML后面的cs文件中,添加以下内容:
// Constructor
public SettingsWindow()
{
InitializeComponent();
Closing += SettingsWindow_Closing; // Subscribe to window closing event.
}
// Window closing event handler.
private void SettingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Add method you want to run on close here.
}
在XAML后面的cs文件中,添加以下内容:
// Constructor
public SettingsWindow()
{
InitializeComponent();
Closing += SettingsWindow_Closing; // Subscribe to window closing event.
}
// Window closing event handler.
private void SettingsWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
// Add method you want to run on close here.
}
如果有视图模型,也可以从视图模型访问它。像这样
Application.Current.MainWindow.Closing += (s, e) =>{ your code comes here};
如果有视图模型,也可以从视图模型访问它。像这样
Application.Current.MainWindow.Closing += (s, e) =>{ your code comes here};
发布一些代码,以便我们可以看到您正在尝试做什么/捕获什么?我对WPF没有做太多的工作,但是您应该能够使用(MyForm mf=new MyForm()){if(mf.ShowDialog()==DialogResults.OK)//do stuff}来做一些事情。这更多的是WinForms的东西,但同样没有看到您正在尝试什么…是吗?发布一些代码,以便我们可以看到您正在尝试做什么/捕获什么?我对WPF没有做太多的工作,但是您应该能够使用(MyForm mf=new MyForm()){if(mf.ShowDialog()==DialogResults.OK)//do stuff}来做一些事情。这更多的是WinForms的东西,但同样没有看到您正在尝试什么…是吗?重写OnClose不包括对象senderI建议在检查条件之前调用基类方法,以防它设置
e.Cancel=false
@Clemens——虽然这是一个很好的观点,但关于这应该走哪条路还存在争议。在某些情况下,程序员经常希望派生类将Cancel重置为false。据我所知,默认的OnClosing事件不会更改为Cancel,因此更改它的唯一方法是如果您已将派生类编程为这样做。重写OnClosing不包括对象senderI建议在检查条件之前调用基类方法,以防它设置e.Cancel=false
@Clemens——虽然这是一个很好的观点,但关于这应该走哪条路还存在争议。在某些情况下,程序员经常希望派生类将Cancel重置为false。据我所知,默认的OnClosing事件不会更改为Cancel,因此更改它的唯一方法是,如果您已将派生类编程为这样做。