【问题标题】:Handle closing event of all windows in wpf处理wpf中所有窗口的关闭事件
【发布时间】:2018-11-12 09:22:44
【问题描述】:

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

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

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

【问题讨论】:

标签: c# .net wpf events eventhandler


【解决方案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>

【讨论】:

  • 虽然继承似乎是一种下降的方式,但我讨厌为可视化类(如窗口、按钮等)这样做,因为当用户没有普通 GPU 时,可以在 UX 中感知到继承的开销
  • 我也讨厌这个,因为 XAML 中不存在可视继承。我能想到的唯一另一件事是您将附加到每个窗口的附加行为。
【解决方案2】:

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

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

【讨论】:

  • 不幸的是我不能使用卸载事件,因为我想在关闭事件中取消关闭
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
相关资源
最近更新 更多