简体   繁体   中英

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);
    }

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;
    }

Your custom EventHandlers need to contain the required signature of the methods. In other words: ToolStripMenuItemClick requires a method with the signature

delegate void EventHandler(object Sender, EventArgs e);

so you'll need to alter the signature of your delegate and the corresponding method.

See here for further reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM