Search code examples
c#winformsdelegatesmenuitemmenustrip

How do I create a delegate to assign to the onClick event of a dynamic menu?


I want to do the following, but I receive an error arguement type DoWindow is not assignable to parameter System.EventHandler

How do I get my delegate to inherit from System.EventHandler?

 public delegate void DoWindow(MdiLayout layoutInstruction) ;

 private ToolStripMenuItem MakeWindowMenu()
    {
        var tsi = new ToolStripMenuItem("Window");
        tsi.DropDownItems.Add(CreateMenuItem("Cascade","Cascade the features",    DoWindowLayout(MdiLayout.Cascade)));
        tsi.DropDownItems.Add(CreateMenuItem("Tile Vertical","Tile the features vertically", this.DoWindowTileVertically));

       //etc
        return tsi;
    }


private   ToolStripMenuItem CreateMenuItem(string Caption, string tooltip, EventHandler onClickEventHandler)
    {
        var item = new ToolStripMenuItem(Caption);
        item.Click += onClickEventHandler;
        item.ToolTipText = tooltip;
        return item;
    }

public DoWindow DoWindowLayout(MdiLayout layoutInstruction)
    {
        Master.MDIForm.LayoutMdi(layoutInstruction);
    }

Solution

  • You could use an Action as the parameter and use an anonymous Eventhandler to invoke the Action

    Something like:

        private ToolStripMenuItem MakeWindowMenu()
        {
            var tsi = new ToolStripMenuItem("Window");
            tsi.DropDownItems.Add(CreateMenuItem("Cascade", "Cascade the features", () => Master.MDIForm.LayoutMdi(MdiLayout.Cascade)));
            tsi.DropDownItems.Add(CreateMenuItem("Tile Vertical", "Tile the features vertically", () => {  }));
            return tsi;
        }
    
        private ToolStripMenuItem CreateMenuItem(string Caption, string tooltip, Action onClickEventHandler)
        {
            var item = new ToolStripMenuItem(Caption);
            item.Click += (s, e) => { onClickEventHandler.Invoke(); };
            item.ToolTipText = tooltip;
            return item;
        }