Reuse a ToolStripMenu for a ToolStrip or a ContextMenuStrip?
In my application, I have a ToolStripMenu (File, Edit, Notes), a ToolStrip right above my work area and a context menu for the work area 开发者_JAVA百科itself. Now the Notes ToolStripMenu, the ToolStrip and the ContextMenuStrip all have the same content that performs the same actions. I was wondering, is there an elegant way to just design the ToolStripMenu and have the other two "mirror" it's function and content instead of rewriting everything 3 times? I saw that all 3 controls use ToolStripItems and ToolStripItemCollections and as such I would think this would be quite easy to do, but the properties are mostly read only, and if I try to loop through one's item to add them to the other, they are removed from the initial owner, and there are no Clone method for ToolStripItems.
Thanks.
Create a method that re-uses your items, actions, etc...
public MainForm()
{
//in your constructor, create all your common methods, actions, etc and save them to private vars
//Then in your form:
ToolStripMenu menu = new ToolStripMenu();
AttachCommonFunctionality(menu);
Items.Add(menu);
ContextMenuStrip rightClick = new ContextMenuStrip();
AttachCommonFunctionality(rightClick);
this.ContextMenu = rightClick;
//etc...
}
private void AttachCommonFuntionality(Control c)
{
c.Items.Add(_item1);
c.Items.Add(_item2);
//etc...
c.OnClick += _myCommonAction;
//etc...
}
精彩评论