0

在 WPF 中为所有窗口注册一个事件,这样的东西应该写在 App 类中:

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

但是Window类没有任何处理Closing事件的属性

4

2 回答 2

1

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>
于 2018-11-12T14:14:29.830 回答
0

注册到 Unloaded 事件怎么样?它有自己的财产。例如:

EventManager.RegisterClassHandler(typeof(Window), PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown));
EventManager.RegisterClassHandler(typeof(Window), UnloadedEvent, new RoutedEventArgs( ... ));
于 2018-11-12T11:21:46.473 回答