自定义用户控制如何将数据发送到托管表单

时间:2014-08-18 19:54:03

标签: c# winforms

我使用c#实现了自定义用户控件。这个控件有一个按钮。 然后将控件添加到具有列表框的WinForm Form1中。

问题是:当我点击用户控件中的按钮时,如何在列表框中添加一些值?

2 个答案:

答案 0 :(得分:2)

单击按钮时,必须从用户控件引发事件,然后在form1中捕获它。

您可以这样做:

用户控制

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

答案 1 :(得分:2)

正如@Jonsey和@Vinc P.建议的那样,你应该使用事件来完成你的工作。

基本上,工作流程是:

  1. 用户触发按钮上的点击事件 ;
  2. 自定义用户控件获取事件,处理它,然后将其传递给其父项,即表单;
  3. 表单获取事件并处理它。
  4. 要实现工作流程,我们可以执行以下操作:

    在用户控制中 我们需要为要注册的表单定义委托和事件:

    public delegate void ButtonClickEventDelegate(object sender, EventArgs e);
    public event ButtonClickEventDelegate ButtonClick;
    

    接下来,我们需要注册按钮点击事件处理程序

    // 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
    }
    

    好的,完成的事情:)