处理 wpf 中所有 windows 的关闭事件

Handle closing event of all windows in wpf

在 WPF 中为所有 window 注册一个事件应该在 App class 中写这样的东西:

EventManager.RegisterClassHandler(typeof(Window), Window.PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));

但是Windowclass没有任何属性来处理Closing事件

注册 Unloaded 活动怎么样?它有自己的 属性。例如:

EventManager.RegisterClassHandler(typeof(Window), PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
EventManager.RegisterClassHandler(typeof(Window), UnloadedEvent, new RoutedEventArgs( ... ));

Window 确实有一个您可以取消的 Closing 事件,但它不是 RoutedEvent,因此您不能以这种方式订阅它。

您始终可以继承 Window 并在一个地方订阅关闭。所有继承 Windows 也将继承此行为。

编辑

这也可以通过行为来完成。 确保安装名为 Expression.Blend.Sdk 的 NuGet 包。 比这样创建附加行为:

using System.Windows;
using System.Windows.Interactivity;

namespace testtestz
{
    public class ClosingBehavior : Behavior<Window>
    {
        protected override void OnAttached()
        {
            AssociatedObject.Closing += AssociatedObject_Closing;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Closing -= AssociatedObject_Closing;
        }

        private void AssociatedObject_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = MessageBox.Show("Close the window?", AssociatedObject.Title, MessageBoxButton.OKCancel) == MessageBoxResult.Cancel;
        }
    }
}

比在你的 XAML 添加这样的行为:

<Window x:Class="testtestz.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        xmlns:local="clr-namespace:testtestz"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Behaviors>
        <local:ClosingBehavior/>
    </i:Interaction.Behaviors>
    <Grid>
    </Grid>
</Window>