Communicating from/to usercontrol in tabcontrol in form

[亡魂溺海] 提交于 2020-01-16 00:47:10

问题


I thought C# was hard. Try posting a question in stackoverflow.

I have a listbox and a button in a usercontrol, itself in a tabpage of a tabcontrol, itself on a form. I need to populate the listbox from the form when the button is clicked.

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)?

Thank you guys.


回答1:


Assuming that your question is about WinForms.

For notification: Expose an event on the userControl and link it to the event of the button, form knows it's children.

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.



来源:https://stackoverflow.com/questions/19153710/communicating-from-to-usercontrol-in-tabcontrol-in-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!