委托在Smobiler自定义控件中运用

委托(Delegate)

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。可以将方法当作另一个方法的参数来进行传递。

委托(Delegate)特别用于实现事件和回调方法。所有的委托(Delegate)都派生自 System.Delegate 类。

使用委托,必须满足4个条件:


声明委托类型;
必须有一个方法包含了要执行的代码;
必须创建一个委托实例;
必须调用(invoke)委托实例。


声明委托

委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。

public delegate void MyDelegate (string a);

委托调用

必须先实例化委托,然后再调用。
例如:

public delegate void MyDelegate();
//实例化委托
printString ex1 = new MyDelegate();
//委托调用 通过Invoke()调用,或者可以直接省略
ex1.Invoke();

委托的应用

使用Smobiler的自定义控件时,往往需要在自定义控件中自定义事件,这时就可以运用到委托。
自定义控件的创建可自行查看smobiler官网中自定义控件内容。

应用场景,自定义控件中有button控件,需要点击button触发自定义控件的事件。
我们下面直接看下,如何使用:

partial class ExampleButton :Smobiler.Core.Controls.MobileUserControl
{
/// <summary>
/// 在删除按钮点击时发生
/// </summary>
[Description("在删除按钮点击时发生")]

public event EventHandler ButtonPress;
public ExampleButton() : base()
{
//This call is required by the SmobilerUserControl.
InitializeComponent();
}
private void SmobilerUserControl1_Load(object sender, EventArgs e)
{
button1.Press += (obj, args) => { this.OnButtonPress(); };
}
private void OnButtonPress()
{
if (ButtonPress != null) ButtonPress.Invoke(this, new EventArgs());
}
/// <summary>
/// 一个委托,它表示按钮点击时要调用的方法。
/// </summary>
/// <param name="sender">事件源</param>
/// <param name="e">包含事件数据的 DeletePress</param>
/// <remarks></remarks>
public delegate void EventHandler(object sender, EventArgs e);
}
之后可在Form中添加自定义控件查看:

2
查看自定义控件的事件,我们发现已经添加事件成功:

1

猜你喜欢

转载自blog.51cto.com/14360220/2412576