Single Parent

Quite a few applications have both menu (MenuStrip control) and toolbar (ToolStrip control). Both of these controls have their menu containers. In case of MenuStrip this is ToolStripMenuItem and in case of ToolStrip we can use ToolStripSplitButton to get same effect. Both of those controls share DropDownItems property and with this you could make one ToolStripMenuItem and add it to both:

var newItem = new ToolStripMenuItem("Test");
newItem.Click += new EventHandler(newItem_Click);
toolStripMenuItem1.DropDownItems.Add(newItem);
toolStripSplitButton1.DropDownItems.Add(newItem);

This code looks nice but it does not work. In this case we will get Test added to toolStripSplitButton1 only.

Culprit for this is in SetOwner method (as seen with Reflector):

private void SetOwner(ToolStripItem item) {
    if (this.itemsCollection && (item != null)) {
        if (item.Owner != null) {
            item.Owner.Items.Remove(item);
        }
        item.SetOwner(this.owner);
        if (item.Renderer != null) {
            item.Renderer.InitializeItem(item);
        }
    }
}

As you can see, if item already has an owner, that owner is removed, and only than new owner is set.

Only solution is to create two new items and assign each to their own parent control:

var newItem1 = new ToolStripMenuItem("Test");
newItem1.Click += new EventHandler(newItem_Click);
toolStripMenuItem1.DropDownItems.Add(newItem1);

var newItem2 = new ToolStripMenuItem("Test");
newItem2.Click += new EventHandler(newItem_Click);
toolStripSplitButton1.DropDownItems.Add(newItem2);

While this means that you have two pieces of same code, you can find consolidation in fact that event handler methods can be reused.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.