C# WPF 事件,委托

事件的注册,注销;委托的注册,注销,自定义的委托;

事件注册用 += 例如:button的事件注册

button.Click += new System.EventHandler(this.button1_Click);

事件注销用 -= 例如:button的事件注销

button.Click -= new System.EventHandler(this.button1_Click);

自定义事件,使用delegate自定义函数带参数

事件函数定义

public delegate int MyEventCallDelegate(string id);

事件委托定义

public MyEventCallDelegate OnEventCall{ get; set; }

事件响应

例如上述事件响应在类MyTest中,MyTest中的函数中需要响应这个事件即可使用:

if (null != OnEventCall)
{
    OnEventCall("1");
}

事件注册

例如上述事件委托定义在类MyTest中,MyTest定义一个对象myTest;

/// <summary>
/// 事件注册
/// </summary>
myTest.OnEventCall += EventCalled;

/// <summary>
/// 事件响应函数实现
/// </summary>
private int EventCalled(string id)
{
    //事件内容实现
}

自定义事件,直接使用EventHandler

事件参数定义

public class MyCallEventArgs : EventArgs
{
    public string id { get; set; }
}

定义事件

public event EventHandler<MyCallEventArgs> OnEventCalled;

类中调用

if (null != OnEventCalled)
{
    MyCallEventArgs mcea = new MyCallEventArgs();
    mcea.id = "1";
    OnEventCalled(mcea);
}

类外引用

MyTest.OnEventCalled += MyEventCalled;

private void MyEventCalled(MyCallEventArgs e)
{
    //事件处理
}

类似文章