开发者

C# How to use the EventHandler?

I'm just creating a ContextMenu..

At this line, I don't know what I shall put in the third param (or better: how I have to form it -syntaxly-):

(contextMenuStrip.Items[0] as System.Windows.Forms.ToolStripMenuItem).DropDownItems.Add(contextUnterMenuStrip.Items.Add(exe),null, HERE);

on 'HERE' I have to set an EventHandler onClick

By Example I got this Method:

public void DoSomething()
{
//...
}

How could I call this Method? (Over the Eventhandler?) or do I ha开发者_Python百科ve to make a Method like:

private void button_Click(object sender, RoutedEventArgs e)
{
    //...
}


Don't "call" the method but take its address. Which means omitting the ()

private void menuItem1_Click(object sender, EventArgs e)
{
    //...
}


// your code, I think it misses a few ')'
... (contextMenuStrip.Items[0] as System.Windows.Forms.ToolStripMenuItem)
       .DropDownItems.Add(contextUnterMenuStrip.Items
       .Add(exe),null, menuItem1_Click);


As you can see here, the callback has to have the following prototype:

public delegate void EventHandler( Object sender, EventArgs e )

So your method DoSomething has to look like:

private void DoSomething(object sender, EventArgs e)
{
    //...
}


You can create an anonymous event handler using the Linq libraries and call your method that way. This can be a nice and quick way of doing something (especially if it's just a test project). But if you start using it extensively, it might become difficult to read it.

An example of this would be:

var menuItem1 = new MenuItem();
menuItem1.Click += (sender, e) => DoSomething();

Refer here for further information on using Linq: http://msdn.microsoft.com/library/bb308959.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜