问题描述
private void toolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
string clickedtext = e.ClickedItem.Name;
if (clickedtext.Contains("saveToolStripButton"))
{
MessageBox.Show(clickedtext);
}
}
我试图按上述方法解决,但我想要更高级的版本处理工具条中的每个工具条按钮如果可能的话,可以在menustrip中使用相同的事件
我尝试过:
ToolStripItemClickedEventArgs e)
{
string clickedtext = e.ClickedItem.Name;
if(clickedtext.Contains (saveToolStripButton))
{
MessageBox.Show(clickedtext);
}
}
我试图按上述方法解决,但我想要更高级的版本来处理工具条中的每个工具条,如果可能的话,可以在menustrip中使用相同的事件
I tried to solve as above but I want more advanced version to handle each toolstripbutton in toolstrip if possible same event can be used in menustrip
What I have tried:
ToolStripItemClickedEventArgs e)
{
string clickedtext = e.ClickedItem.Name;
if (clickedtext.Contains("saveToolStripButton"))
{
MessageBox.Show(clickedtext);
}
}
I tried to solve as above but I want more advanced version to handle each toolstripbutton in toolstrip if possible same event can be used in menustrip
推荐答案
private delegate void ToolStripButtonMethod();
设置项目点击方法以使用它:
Set up your item clicked method to use it:
private void myToolStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
ToolStripButton tsb = e.ClickedItem as ToolStripButton;
if (tsb != null)
{
ToolStripButtonMethod d = tsb.Tag as ToolStripButtonMethod;
if (d != null)
{
d();
}
}
}
然后创建执行按钮操作的方法:
Then create the methods to perform the button operations:
private void DoTheSave() { Console.WriteLine("Save"); }
private void DoTheSaveAs() { Console.WriteLine("Save As"); }
最后将它们添加到按钮:
And finally add them to your buttons:
private void LoadEm()
{
tsbSave.Tag = new ToolStripButtonMethod(DoTheSave);
tsbSaveAs.Tag = new ToolStripButtonMethod(DoTheSaveAs);
}
凌乱?是。明显?没有。工作?是的......但是你必须记得在更换工具条时添加每个新按钮。
我?我将使用单独的ToolStripButton.Click处理程序...
Messy? Yes. Obvious? No. Works? Yes...but you will have to remember to add each new button when you change your toolstrip.
Me? I'd use the individual ToolStripButton.Click handlers...
这篇关于如何在工具条中为每个工具条按钮编写常见事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!