在C#中如何以编程方式连接ToolStripButton事件? [英] How do I programmatically wire up ToolStripButton events in C#?
问题描述
这部分很简单。 $ p> this.tsmiDelete.DropDownItems.Add(项目上的文字);
但是,我还需要连接事件,以便用户点击实际发生的事情时!
我该怎么做?处理点击的方法还需要接收与用户点击的特定ToolStripButton相关的某种id或对象。
p>你不能订阅Click事件吗?这样的东西:
ToolStripButton btn = new ToolStripButton(项目上的文字);
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click + = new EventHandler(OnBtnClicked);
OnBtnClicked将被声明为:
private void OnBtnClicked(object sender,EventArgs e)
{
ToolStripButton btn = sender as ToolStripButton;
//处理按钮点击
}
发件人应该是ToolStripButton,所以你可以投掷它,并做任何你需要做的事情。
I'm programmatically adding ToolStripButton items to a context menu.
That part is easy.
this.tsmiDelete.DropDownItems.Add("The text on the item.");
However, I also need to wire up the events so that when the user clicks the item something actually happens!
How do I do this? The method that handles the click also needs to receive some sort of id or object that relates to the particular ToolStripButton that the user clicked.
Couldn't you just subscribe to the Click event? Something like this:
ToolStripButton btn = new ToolStripButton("The text on the item.");
this.tsmiDelete.DropDownItems.Add(btn);
btn.Click += new EventHandler(OnBtnClicked);
And OnBtnClicked would be declared like this:
private void OnBtnClicked(object sender, EventArgs e)
{
ToolStripButton btn = sender as ToolStripButton;
// handle the button click
}
The sender should be the ToolStripButton, so you can cast it and do whatever you need to do with it.
这篇关于在C#中如何以编程方式连接ToolStripButton事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!