Search code examples
c#winformsclasshandler

same click event availalble in different classes


My plan is to devide GUI elements in one class and having a class where those GUI elements will be shown or put on mainform/usercontrol. So what I have to do, when I want to use a click Handler in GUI elements but is original placed in mainform/usercontrol? Or in other words: If its possible to provide the click eventHandler via paramter to GUI element class constructor, how I access it inside GUI elements or create a reference of it that can be used inside GUI elements?

Hope you understood what my primitive goal is.

Addition: Since we are in same namespace is the following possible ? I found that in history and tried and it worked, but involved classes were a Usercontrol and its mainform ( 2 forms ).

class GUI Elements {
  public event Eventhandler ButtenClickedHandler;

  private void ButtonClickHandler(object sender, EventArgs e) {
     if ( this.ButtonClickedHandler != null ) this.ButtonClickedHandler( sender, e )
  }
}

class Example : Usercontrol/Form {
  ...

  GUI Elements gE = new GUI Elements()
  gE.ButtonClickedHandler += new EventHandler( ClickEventhandler )

  public void ClickEventHandler(object sender, EventArgs e) {}
  ...
}

Just a good example that helps to understand the principal of how it must be done.


Solution

  • When registering an event handler it does not have to be in the same class, you can use a method on some other object just fine.

    Also note that the compiler should be able to convert the "method group", i.e. the name of a method, to a compatible delegate just fine without creating an EventHandler explicitly:

    gE.ButtonClickedHandler += gE.ButtonClickHandler;
    

    Or you can just forward the event in the local handler

    public void ClickEventHandler(object sender, EventArgs e) 
        => gE.ButtonClickHandler(sender, e)