Introduction
Ever in the need of grouping multiple ToolStripMenuItem
s together to imitate the behaviour of RadioButton
s? This simple control inherits from ToolStripMenuItem
and adds a new property for grouping them in Design mode. Multiple groups in the same dropdown menu are supported.
Background
When I was first in the need for ToolStripMenuItem
s that behave like RadioButton
s, I did it via events. The second time, I started to wonder why MS didn't provide an additional property for easily grouping ToolStripMenuItem
s together. After a little "Googling", I found an example at MSDN: http://msdn2.microsoft.com/en-us/library/ms404318.aspx.
After reading the article, I realized that this wasn't what I was searching for! They explained how to achieve the desired effect with "CheckOnClick
" and even provided custom drawing for the radio-button layout. That's not standard (but ugly), and not what I wanted! Furthermore, their example didn't support multiple "groups" in the same dropdown menu.
So I started to implement my own solution. It is based on the example at MSDN, but simplifies it wherever possible.
Using the Code
This section should be named "Using the component".
Add the source file to your project. After a rebuild, you should be able to select ToolStripMenuItemGrouped
when designing a ToolStripMenu
.
Basically, I just added a simple property called GroupIndex
. Its default value is 0, which means: no group. For all ToolStripMenuItemGrouped
that belong together, enter a value greater than that. By using different values, it is possible to support more than one group in the same dropdown menu.
Points of Interest
I left the overridden enabled
property of the original sample code by MS. That added the possibility to automatically enable/disable all ToolStripMenuItemGrouped
subitems when the owner control (ToolStripMenuItem)
changed its checked-state. You can try it out by adding ToolStripMenuItemGrouped
items to the dropdown of a ToolStripMenuItem
. Then set the CheckOnClick
property of the owner to "true
". At runtime, the subitems will automatically change their enabled
state, whether the owner is checked or not.
To add the new class to the designer, I simply had to provide the following attribute:
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip)]
Further Reading