扬州建设局网站,wordpress仿p站主题,猎头公司人才招聘,便宜网站空间一、目的#xff1a;在WPF中如何注册控件级全局事件和应用程序级全局事件 二、实现
应用程序级全局事件
//注册应用程序级全局事件
EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandler(ic_event_Click));
如上代码既会注册全局…一、目的在WPF中如何注册控件级全局事件和应用程序级全局事件 二、实现
应用程序级全局事件
//注册应用程序级全局事件
EventManager.RegisterClassHandler(typeof(Button), Button.ClickEvent, new RoutedEventHandler(ic_event_Click));
如上代码既会注册全局Button的Click事件在任意位置点击Button既会触发注册的事件但这种方式作用范围过大对于有些业务来说这种方式会照成资源和性能上的浪费本文将主要介绍空间级别的全局事件这对于某功能来说既可以实现特殊的业务也可以有效的控制性能。
控件级全局事件
比如有一个ItemsControl控件绑定了一个集合集合里面有很多Button操作的按钮我们想要注册这些按钮的Click操作这时需要用到控件级别的全局Button的Click事件。代码如下 ItemsControl ItemsSource{h:GetStudents}ItemsControl.ItemTemplateDataTemplateButton Content{Binding Name}//DataTemplate/ItemsControl.ItemTemplate/ItemsControl 主要实现方式有两种
1 在Xaml中实现 ItemsControl x:Nameic_event ButtonBase.ClickItemsControl_Button_Click ItemsSource{h:GetStudents}ItemsControl.ItemTemplateDataTemplateButton Content{Binding Name}//DataTemplate/ItemsControl.ItemTemplate/ItemsControl private void ItemsControl_Button_Click(object sender, RoutedEventArgs e){if (e.OriginalSource is Button button)MessageBox.Show(button.Content?.ToString());} 可以看到直接在ItemsControl上注册Button.Click事件即可实现该效果此时当点击控件中任意Button时会触发该事件
2在代码中实现
//在代码中注册控件级全局事件
this.ic_event.AddHandler(Button.ClickEvent, new RoutedEventHandler(ItemsControl_Button_Click));
在代码中实现也比较简单只需应用AddHandler方法注册一个Button.ClickEvent即可实现
总结
1、通过这种方式可以解决部分特殊业务如上述示例中可以注册控件内所有按钮点击事件而不需要对每个按钮单独做处理
2、不仅仅局限Button.Click事件任何路由事件和附加事件均可通过上述方式实现
3、可以实现没有暴露出来的鼠标键盘触摸板等应用附加事件定义的功能进行注册如 ItemsControl x:Nameic_event Mouse.GotMouseCaptureic_event_GotMouseCapture ItemsSource{h:GetStudents}ItemsControl.ItemTemplateDataTemplateButton Content{Binding Name}//DataTemplate/ItemsControl.ItemTemplate/ItemsControl ItmsControl没有暴露GotMouseCapture事件可以通过Mouse.GotMouseCapture去注册该事件
三、效果 需要了解的知识点
EventManager Class (System.Windows) | Microsoft Learn
EventManager.RegisterClassHandler 方法 (System.Windows) | Microsoft Learn
ButtonBase.Click 事件 (System.Windows.Controls.Primitives) | Microsoft Learn
UIElement.AddHandler 方法 (System.Windows) | Microsoft Learn
UIElement.RemoveHandler(RoutedEvent, Delegate) Method (System.Windows) | Microsoft Learn
Mouse 类 (System.Windows.Input) | Microsoft Learn
Keyboard 类 (System.Windows.Input) | Microsoft Learn
System.Windows.Controls 命名空间 | Microsoft Learn控件库 - WPF .NET Framework | Microsoft Learn
WPF 介绍 | Microsoft Learn
XAML概述 - WPF .NET | Microsoft Learn
Windows Presentation Foundation 简介 - WPF .NET | Microsoft Learn
使用 Visual Studio 创建新应用教程 - WPF .NET | Microsoft Learn
源码地址
GitHub - HeBianGu/WPF-ControlDemo: 示例
GitHub - HeBianGu/WPF-ControlBase: Wpf封装的自定义控件资源库
GitHub - HeBianGu/WPF-Control: WPF轻量控件和皮肤库
了解更多
适用于 .NET 8 的 WPF 的新增功能 - WPF .NET | Microsoft Learn
适用于 .NET 7 的 WPF 的新增功能 - WPF .NET | Microsoft Learn
System.Windows.Controls 命名空间 | Microsoft Learn
欢迎使用 Expression Blend | Microsoft Learn
https://github.com/HeBianGu
HeBianGu的个人空间-HeBianGu个人主页-哔哩哔哩视频