当前位置:网站首页>【wpf】自定义事件总结(Action, EventHandler)
【wpf】自定义事件总结(Action, EventHandler)
2022-08-10 00:54:00 【code bean】
Action和EventHandle
Action和EventHandler都是.net帮我定义好的委托,我们可以直接使用,方便的定义事件。
利用Action定义事件
//无参事件
event Action Event1;
//有参事件
event Action<int, int, string> Event2;
事件订阅和事件处理
public 事件测试()
{
InitializeComponent();
// 事件的订阅
Event1 += 事件测试_Event1;
Event2 += 事件测试_Event2;
}
private void 事件测试_Event1()
{
MessageBox.Show("事件测试_Event1");
}
private void 事件测试_Event2(int arg1, int arg2, string arg3)
{
MessageBox.Show($"{arg1 + arg2} {arg3}");
}
事件的触发
private void btn1_Click(object sender, RoutedEventArgs e)
{
//事件的触发
Event1?.Invoke();
}
private void btn2_Click(object sender, RoutedEventArgs e)
{
//事件的触发
Event2?.Invoke(1, 2, "test");
}
这里通过Invoke调用和直接调用,效果和效率都是一样的,这样写凸显出这是这个事件的触发,事件后的问号表示,如果事件为空就不触发的一种简单写法。
EventHandler
EventHandler,在.net6中感觉和Action的区别已经不大了,调用时有些差别(见下面代码)。之前的版本中只有用EventHandler定义的事件才能在Xaml中使用,在.net6使用Action定义的事件也可以在Xaml中使用了。
这里我定义了一个控件,并分别通过两种方式定义了事件
public class Class1 : Button
{
public event Action EventTest;
public event EventHandler<string> Event3;
protected override void OnClick()
{
EventTest?.Invoke();
Event3?.Invoke(this, "123"); // 事件的调用方式稍有不同
base.OnClick();
}
}
发现在前台Xaml都是可以直接使用的:
<local:Class1 EventTest="Class1_EventTest" Event3="Class1_Event3" >Class1</local:Class1>private void Class1_EventTest()
{
MessageBox.Show("Class1_EventTest");
}
private void Class1_Event3(object sender, string e)
{
MessageBox.Show($"Class1_Event3: {e}");
}
小结:
可以说通过Action和EventHandle,自定义事件是相当的方便简单了。
边栏推荐
猜你喜欢

Chip Information|Semiconductor revenue growth expected to slow to 7%, Bluetooth chip demand still growing steadily

y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)

ITK编译remote库

RedHat红帽RHEL7安装与使用,VMware Workstation16 Pro虚拟机的安装与使用

【CAS:41994-02-9 |Biotinyl tyramide】Biotinyl tyramide price

Unity editor extension interface uses List

Mysql database ALTER basic operations

Sikuli's Automated Testing Technology Based on Pattern Recognition

小程序中计算距离信息

墨西哥大众VW Mexico常见的几种label
随机推荐
DHCP——动态主机配置协议
y92.第六章 微服务、服务网格及Envoy实战 -- Envoy基础(三)
Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)
SonarQube升级记录:7.8->7.9->8.9
删除表空间数据文件
Sikuli's Automated Testing Technology Based on Pattern Recognition
【Grpc】报错:status = StatusCode.UNIMPLEMENTED details = ““
小程序实现搜索功能续
XSS详解及复现gallerycms字符长度限制短域名绕过
商业模式及其 SubDAO 深入研究
Pyscript,创建一个能执行crud操作的网页应用
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
Sikuli 基于图形识别的自动化测试技术
Unity image is blurry after using long image
CAS:851113-28-5 (Biotin-ahx-ahx-tyramine)
Not, even the volume of the king to write code in the company are copying and pasting it reasonable?
Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
[转] Typora_Markdown_图片标题(题注)
UI遍历的初步尝试
Summary of basic operations of c language files