I’m working on a little project to learn the ins & outs of Winforms 2.0, and I’ll be posting in the near future (well, I think I’ll be posting stuff in the near future) on the surprises and gotchas I encountered; oh, and the cool stuff, too.
The first surprise, and coolness, is with the new MenuStrip control. Menus and toolbars got a huge makeover for 2.0. We got Win98 menus in 1.1; now, we have Office 2003 menus complete with themes, textboxes, comboboxes and CommandBars. Funny that we get all those things after the Office team abandons them, which is not to say that they aren’t useful. So the feature set is way bigger, and there is some translation needed. This article on CodeProject is very helpful for that translation for menus and toolbars.
So, what’s the weirdness? Well, I want to enable/disable a menu item based on whether some object is null. I’d do this in 1.1 with the MenuItem.Popup event. The article linked above says the Popup event on the MenuItem translates to the ToolStripDropDownItem.DropDownOpening event; ToolStripMenuItem inherits from ToolStripDropDownItem. I hook up the following event handler to my ToolStripMenuItem:
private void myToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
{
myToolStripMenuItem.Enabled = someObject != null;
}
Looks normal, right? And, it works, but the event is raised at, it seems, arbitrary times which isn’t what I expected. I’d open the menu, let the mouse dance around a bit, then as soon as I pointed the mouse on that menu item, it would be disabled. That’s the weirdness. You can probably tell that this is not desirable behaviour: imagine your user clicks the menu, points her mouse at your terrific new feature in the menu but when she gets to it, it becomes disabled. That ain’t cool. So, I think I’m doing something wrong; I just can’t bring myself to believe that Microsoft would ship something that broken.
Now, I was hacking away, and I didn’t want to let this stop me, so I found a workaround which demonstrates some new coolness. The MenuStrip has a MenuActivated event that’s raised before it shows the menu, so I figured I’d try that event. This time, I’d have to find my menu item and then set the property, and that is the coolness. Jessica (aka jfo) explains the keyed collection that WinForms 2.0 gives you for every control. So I hook up the following event handler to the MenuStrip.MenuActivated event:
private void menuStrip1_MenuActivate(object sender, EventArgs e)
{
MenuStrip menu = (MenuStrip)sender;
ToolStripItem[] item = (ToolStripItem[])menu.Items.Find(“myToolStripMenuItem”, true);
item[0].Enabled = someObject != null;
And that works like a charm. The boolean parameter is for searching all children, which is what I want. Passing false there only searches the top-level menu.
Now playing: Watchmen – Any Day Now
Technorati Tags: Winforms, Windows Forms, MenuStrip, ToolStripMenuItem