为C#自定义控件添加自定义事件

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

为C#自定义控件添加自定义事件

展开全文

用户控件的实现比较简单,直接从erControl继承。

public class UserControl1 : erControl

为了便于测试我在上面添加了一个TextBox,并注册TextBox的TextChanged事件,

this.textBox1.TextChanged += new System.EventHandler(this.textBox1_T extChanged);

事件处理函数,

private void textBox1_TextChanged(object sender, System.EventArgs e)

{

MessageBox.Show(this.textBox1.Text);

}

这里演示如果控件中文本框的内容改变就会用MessageBox显示当前的文本框内容。

窗体中添加上面的用户控件,当我们改变textBox的文本时,可以看到跳出一个对话框,很简单吧。

下面来看看对控件添加属性。

这里定义一个私有变量。

private string customValue;

添加访问他的属性

public string CustomValue

{

get{return customValue;}

set{customValue =value;}

}

在窗体中使用的时候像普通控件一样进行访问,

userControl11.CustomValue = "用户控件自定义数据";

通过事件可以传递消息到窗体上,在定义之前我们先来写一个简单的参数类。

public class TextChangeEventArgs : EventArgs

{

private string message;

public TextChangeEventArgs(string message)

{

this.message = message;

}

public string Message

{

get{return message;}

}

}

定义委托为,

public delegate void TextBoxChangedHandle(object sender, TextChangeEventArgs e);

接下去在用户控件中添加事件,

//定义事件

public event TextBoxChangedHandle UserControlValueChanged;

为了激发用户控件的新增事件,修改了一下代码,

private void textBox1_TextChanged(object sender, System.EventArgs e)

{

if(UserControlValueChanged != null)

UserControlValueChanged(this,new TextChangeEventArgs(t

his.textBox1.Text));

}

好了,为了便于在Csdn上回答问题,把完整的代码贴了出来:

using System;

using System.Collections;

using ponentModel;

using System.Drawing;

using System.Data;

using System.Windows.Forms;

namespace ZZ.WindowsApplication1

{

public class UserControl1 : erControl

{

private System.Windows.Forms.TextBox textBox1;

private string customValue;

private ponentModel.Container

components = null;

public string CustomValue

{

get{return customValue;}

set{customValue =value;}

}

//定义事件

public event TextBoxChangedHandle UserControlValueChanged;

public UserControl1()

{

InitializeComponent();

}

protected override void Dispose( bool disposing )

{

if( disposing )

{

if(components != null)

{

components.Dispose();

}

}

base.Dispose( disposing );

}

#region组件设计器生成的代码

private void InitializeComponent()

{

this.textBox1 = new System.Windows.Forms.TextBox();

this.SuspendLayout();

this.textBox1.Location = new System.Drawing.Point(12, 36);

= "textBox1";

this.textBox1.TabIndex = 0;

this.textBox1.Text = "textBox1";

this.textBox1.TextChanged

+= new System.EventHandler(this.textBox1_TextChanged);

this.Controls.Add(this.textBox1);

= "UserControl1";

this.Size = new System.Drawing.Size(150, 92);

this.ResumeLayout(false);

}

#endregion

相关文档
最新文档