It is possible to pass data to EventArgs without creating derived class?

前端 未结 3 1114
梦如初夏
梦如初夏 2021-02-19 07:27

I am a bit confused. I know I can create class derived from EventArgs in order to have custom event data. But can I employ the base class EventArgs somehow? Like the mouse butto

3条回答
  •  半阙折子戏
    2021-02-19 08:24

    You can use the EventArgs class through the Generic Types approach. In this sample, i will use the Rect class with as return type:

    public EventHandler SizeRectChanged;
    

    Raising the event:

    if(SizeRectChanged != null){
       Rect r = new Rect(0,0,0,0);
       SizeRectChanged(this,r);
    }
    

    Listening the event:

    anyElement.SizeRectChanged += OnSizeRectChanged;
    
    public void OnSizeRectChanged(object sender, Rect e){
        //TODO abything using the Rect class
        e.Left = e.Top = e.Width = e.Height = 50;
    }
    

    So, don't need to create new events classes or delegates, simply create a EventHandler passing the specific type T.

提交回复
热议问题