【发布时间】:2014-10-11 19:44:11
【问题描述】:
我已经使用 c# 实现了一个自定义用户控件。这个控件有一个按钮。 然后将该控件添加到具有列表框的 WinForm Form1 中。
问题是:当我单击用户控件中的按钮时,如何在列表框中添加一些值?
【问题讨论】:
-
从用户控件引发事件
我已经使用 c# 实现了一个自定义用户控件。这个控件有一个按钮。 然后将该控件添加到具有列表框的 WinForm Form1 中。
问题是:当我单击用户控件中的按钮时,如何在列表框中添加一些值?
【问题讨论】:
当您单击按钮时,您必须从用户控件中引发一个事件,然后在您的表单中捕获它1。
你可以这样做:
用户控制
public event EventHandler CLickFromUserControl;
private void click_event_on_the_button()
{
//Null check makes sure the main page is attached to the event
if (this.CLickFromUserControl != null)
this.CLickFromUserControl(new object(), new EventArgs());
}
Form1
public MyApp()
{
//USERCONTROL = your control with the CLickFromUserControl event
this.USERCONTROL.CLickFromUserControl += new EventHandler(MyEventHandlerFunction_CLickFromUserControl);
}
public void MyEventHandlerFunction_CLickFromUserControl(object sender, EventArgs e)
{
//add the value here
}
您可以向事件传递更多参数:
this.CLickFromUserControl(new object(), new EventArgs(), param1, param2);
然后是形式:
public void MyEventHandlerFunction_CLickFromUserControl(object sender, EventArgs e, string param 1, string param2)
{
//add the value here
}
或
您可以在用户控件上创建属性:
public string Value {
get { return textBox1.Text; }
set { textBox1.Text = value; }
}
然后在表单的事件中从发送者那里访问它。
您可以查看如何构建活动:msdn
【讨论】:
正如@Jonsey 和@Vinc P. 所建议的,您应该使用Event 来完成您的工作。
基本上,工作流程是:
要实现工作流,我们可以做到以下几点:
在用户控制中 我们需要为要注册的表单定义委托和事件:
public delegate void ButtonClickEventDelegate(object sender, EventArgs e);
public event ButtonClickEventDelegate ButtonClick;
接下来我们需要注册Button Click Event Handler:
// in the custom user control constructor
public CustomUserControl()
{
InitializeComponent();
Button.Click += ButtonClickHandler;
}
接下来我们需要在用户控件中定义按钮点击的行为:
private void ButtonClickHandler(object sender, EventArgs e)
{
// do some handling if you have
// now the important part, call the delegate function here, it will pass the handle to
// the behavior defined in the main form:
if (ButtonClick != null) ButtonClick(this, e);
}
现在我们已经完成了用户控制部分,接下来是关于托管表单。 我们需要做的事情很简单:注册并定义ButtonClick的行为:
// in main form's constructor
public Form1()
{
InitializeComponent();
CustomUserControl.ButtonClick += UserControlButtonClickHandler();
}
private void UserControlButtonClickHandler(object sender, EventArgs e)
{
// add the value here
}
好的,事情完成了:)
【讨论】: