当前位置:网站首页>【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,自定义事件是相当的方便简单了。
边栏推荐
猜你喜欢

鲜花线上销售管理系统的设计与实现

以太网PHY芯片LAN8720A芯片研究

多线程之自定义线程池

Not, even the volume of the king to write code in the company are copying and pasting it reasonable?

Experimental support for decorators may change in future releases.Set the "experimentalDecorators" option in "tsconfig" or "jsconfig" to remove this warning

彩色袜子题

Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate

assert利用蚁剑登录

What should I do if there is no sound after reinstalling the system in win10?

How to add control panel to right click menu in win7
随机推荐
Stanford CS143 Speed Pass PA1 Tutorial
-Vector Dot Product-
Biotin-Cy2 Conjugate, Biotin-Cy2 Conjugate_Cy2 Biotin Conjugate
Involved in PEG-Biotin (CAS: 1778736-18-7) Biotin-PEG4-OH is widely used in molecular target detection
C language pointer practice questions
-Chess game-
R语言使用coxph函数构建生存分析回归模型,使用forestmodel包的forest_model函数可视化生存回归模型对应的森林图
[LeetCode] Find the sum of the numbers from the root node to the leaf node
Initial attempt at UI traversal
assert利用蚁剑登录
墨西哥大众VW Mexico常见的几种label
Penetration Testing and Offensive and Defense Confrontation - Vulnerability Scanning & Logic Vulnerability (Part1)
C language structure, function and pointer exercise (simple address book)
你有对象类,我有结构体,Go lang1.18入门精炼教程,由白丁入鸿儒,go lang结构体(struct)的使用EP06
Pyscript,创建一个能执行crud操作的网页应用
el-input保留一位小数点
【ROS2原理10】Interface数据的规定
使用 GoogleTest 框架对 C 代码进行单元测试
-red and black-
手把手教你编写性能测试用例