委託在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

相關文章
相關標籤/搜索