2010-06-21 13 views
2

在我的應用程序中,我有一個ToolStripMenu(文件,編輯,註釋),一個ToolStrip正好在我的工作區上方,還有一個工作區本身的上下文菜單。現在Notes ToolStripMenu,ToolStrip和ContextMenuStrip都具有執行相同操作的相同內容。我想知道,是否有一種優雅的方式來設計ToolStripMenu,並讓另外兩個「鏡像」它的功能和內容,而不是重寫所有內容3次?我看到所有3個控件都使用了ToolStripItems和ToolStripItemCollections,因此我認爲這很容易實現,但是這些屬性大多是隻讀的,如果我嘗試循環通過某個項目將它們添加到另一個項目中,它們是從最初的所有者中刪除,並且ToolStripItems沒有克隆方法。爲ToolStrip或ContextMenuStrip重新使用ToolStripMenu?

謝謝。

回答

1

創建的方法重新使用您的項目,行動等......

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... 
} 
+0

猜我不得不這樣做的,謝謝。 – 2010-06-22 02:25:46