简体   繁体   English

以tabcontrol形式从/向usercontrol进行通信

[英]Communicating from/to usercontrol in tabcontrol in form

I thought C# was hard. 我认为C#很难。 Try posting a question in stackoverflow. 尝试在stackoverflow中发布问题。

I have a listbox and a button in a usercontrol, itself in a tabpage of a tabcontrol, itself on a form. 我在usercontrol中有一个列表框和一个按钮,它本身位于tabcontrol的一个tabpage中,它本身就在一个表单上。 I need to populate the listbox from the form when the button is clicked. 单击按钮时,我需要从表单填充列表框。

form > tabcontrol > tabpage > usercontrol > listbox & button form> tabcontrol> tabpage> usercontrol> listbox&button

So, how do you notify the form that a deeply buried button has been clicked and then fill the listbox from the form (or call the usercontrol from the form to populate the listbox)? 那么,如何通知表单已经点击了深埋的按钮,然后填写表单中的列表框(或者从表单调用usercontrol来填充列表框)?

Thank you guys. 感谢大伙们。

Assuming that your question is about WinForms. 假设你的问题是关于WinForms的。

For notification: Expose an event on the userControl and link it to the event of the button, form knows it's children. 对于通知:在userControl上公开一个事件并将其链接到按钮事件,表单知道它的子项。

public class MyUserControl {
    private Button myButton;
    public event EventHandler MyControlButtonClicked;

    public MyUserControl() {
         ...
         myButton.Click += OnMyButtonClicked;
    }

    private void OnMyButtonClicked(object sender, EventArgs arguments) {
        if (MyControlButtonClicked != null) {
           MyControlButtonClicked(this, arguments);
        }
    }
}

In your form: 在你的形式:

public class MyForm {
   private MyUserControl userControl;

   public MyForm() {
     ...
     userControl.MyControlButtonClicked += OnUserControlButtonClicked;
   }

   private void OnUserControlButtonClicked(object sender, EventArgs arguments) {
      // handle the button click here
   }
}

For population: The same pattern, use your user control as a mediator. 对于填充:相同的模式,使用您的用户控件作为介体。 Add a public method on userControl that will do the listBox population and call it from your form. 在userControl上添加一个公共方法,该方法将执行listBox填充并从表单中调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM