在创建项目之前,先为其分配功能! [英] assigning a function to an Item before creating it !

查看:61
本文介绍了在创建项目之前,先为其分配功能!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出问题了!
我的程序在运行时将项目添加到MenuStrip
我需要为每个新项提供一个函数,但是...如果项尚未创建,该如何编写调用此函数的代码? 换句话说,
每次我按下按钮时,程序都会在MenuStrip中添加一个项(汽车名称)...我想向用户提供有关他从MenuStrip中选择的汽车的信息!

Such a problem!!!
my program adds Items to a MenuStrip during the RunTime
I need to give a function to each of those new Items but ... how to write a code that calls this function if the Item was not created yet???
in other words,
the program adds an Item (car name) to the MenuStrip each time I press a button ... I want to give the user some information about the Car he chose from the MenuStrip!!!

how can I do that?

推荐答案

显然,您不能向不存在的内容添加任何内容.同样明显的是,您永远不需要它.不存在的东西无济于事.

您的问题很简单.您需要将事件处理程序添加到现有菜单项(刚创建的菜单项)的事件的调用列表中.随便做吧:

Apparently, you cannot add anything to something which does not exist. Equally apparent thing is that you never need it. Something which does not exist cannot help.

Your problem is very simple. You need to add an event handler to an invocation list of an event of the existing menu item, the one you just created. Just do it:

class ToolStripItemData { //it's often helpful to define some data type, to put in each item
//... your car data, for example
}

//...

System.Windows.Forms.ToolStripItem.Click item =
    new System.Windows.Forms.ToolStripDropDownItem(); //for example
item.Tag = new ToolStripItemData(/* ... */); // some data specific to a particular item instance (e.g. car data)

//...

item.Click += (sender, eventArgs) => {
    System.Windows.Forms.ToolStripItem item =
        (System.Windows.Forms.ToolStripItem)sender;
    ToolStripItemData carData = (ToolStripItemData)item.Tag; //make sure you read what you put there
    //some action depending on carData
} //item.Click



如果使用C#v.2,则需要对匿名委托实例使用较旧(较长)的语法,并使用显式类型声明:



In case you use C# v.2, you need to use older (longer) syntax for anonymous delegate instance, with explicit type declaration:

item.Click += delegate(object sender, System.EventArgs eventArgs) {
//...
}



请参见System.Windows.Forms.ToolStripItem.Click: http://msdn.microsoft.com/en -us/library/system.windows.forms.toolstripitem.click.aspx [



See System.Windows.Forms.ToolStripItem.Click: http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripitem.click.aspx[^].

—SA


// You can in ItemAdded event of your menuStrip call your function
private void menuStrip1_ItemAdded(object sender, ToolStripItemEventArgs e)
{
    // Calling your function
}



也许你的意思是这样的:



Perhaps you mean is this:

private void menuStrip1_ItemAdded(object sender, ToolStripItemEventArgs e)
{
    // You can create event handler for each added item during the RunTime
    e.Item.Click += new EventHandler(Item_Click);
}

void Item_Click(object sender, EventArgs e)
{
    // TODO: code
}


这篇关于在创建项目之前,先为其分配功能!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆