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

委托(Delegate)函数

C# 中的委托(Delegate)相似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。能够将方法看成另外一个方法的参数来进行传递。ui

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

使用委托,必须知足4个条件:指针


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


声明委托blog

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

public delegate void MyDelegate (string a);ip

委托调用rem

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

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

相关文章
相关标签/搜索