Introduction
It's very common to have both a menu item and a toolbar button that perform the same action when clicked. Sometimes, there is even a third or fourth control (say a button and a context menu item) that do the same thing. These controls need to be enabled and disabled together.
The code in this article allows each such control to be connected to a UICommand
object by setting a property in the Visual Studio designer. The UICommand
object has an Enabled
property that enables or disables all of the associated controls. It also has an Execute
event that is raised when any of the controls are clicked.
Using the code
Download the demo code. The CommandDemo project contains two classes, UICommand
and UICommandProvider
. Copy the associated files into your project and compile. The classes will appear in the toolbox as seen below whenever the form designer is open:
Begin by dragging an instance of UICommandProvider
onto the form. It will appear in the components area of the designer (near the bottom), as seen in the above screenshot. Only one instance of UICommandProvider
is needed per form. Because UICommandProvider
implements IExtenderProvider
and its CanExtend
method returns true
for any object derived from ToolStripItem
or Control
, the Visual Studio designer adds a new property to those objects. The property is of type UICommand
.
The demo project contains two instances of UICommand
: uiCommand1
and uiCommand2
. Each of these objects is connected to four other controls: a regular button, a tool bar button, a menu item (under the Commands menu), and a context menu item. This was done by dragging two instances of UICommand
onto the form, then setting each control's UICommand
property to the appropriate instance of UICommand
. For example, the following screenshot shows that button2.UICommand
is set to uiCommand2
:
The result is that whenever button2
(or any of the other controls whose UICommand
property is set to uiCommand2
) is clicked, the event uiCommand2
.Execute
is raised. Also, whenever uiCommand2
.Enabled
is set, the Enabled
property of the associated controls is also set.
For the purposes of this demo, the Execute
handler for each UICommand
simply toggles the Enabled
property of the other UICommand
. This makes it easy to see that one line of code enables or disables several controls on the form. Here are the two event handlers:
private void uiCommand1_Execute(object sender, EventArgs e) {
uiCommand2.Enabled = !uiCommand2.Enabled;
}
private void uiCommand2_Execute(object sender, EventArgs e) {
uiCommand1.Enabled = !uiCommand1.Enabled;
}
UICommand
could probably be extended to have an Image
property that causes the associated controls to have the same image (where appropriate), a ToolTip
property that assigns the same tooltip text to all the controls, and so on. I'll leave this as an exercise to the reader.