質問

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.

役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top