C#能给控件增加自定义事件不?怎么增?

C#能给控件增加自定义事件不?怎么增?,第1张

C#中Asp.net和winform都提供有控件,一般控件的自身事件就足够用了。

如果想要给控件自定义事件的话,也没有问题,需要的基础知识就是对delegate和event比较了解。

这样就可以自己写自定义事件。

public class SampleEventArgs

{

public SampleEventArgs(string s) { Text = s}

public String Text {getprivate set} // readonly

}

public class Publisher

{

// Declare the delegate (if using non-generic pattern).

public delegate void SampleEventHandler(object sender, SampleEventArgs e)

// Declare the event.

public event SampleEventHandler SampleEvent

// Wrap the event in a protected virtual method

// to enable derived classes to raise the event.

protected virtual void RaiseSampleEvent()

{

// Raise the event by using the () operator.

if (SampleEvent != null)

SampleEvent(this, new SampleEventArgs("Hello"))

}

}

class usercontrol1:UserControl

{

// 避免和UserControl的Click重名,不过你可以重写UserControl的Click事件

public event EventHandler Click2

// Label1的声明

protected Label Label1

// 构造函数

public usercontrol1()

{

label1 = new Label()

label1.Click += new System.EventHandler(this.label1_Click)

}

....

....

private void label1_Click(object sender, EventArgs e)

{

if (Click2 != null)

{

Click2(this, new EventArgs())

}

}

}

// 补充

按照你的label的名字改一改,


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/bake/11853958.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存