Tip If you want to slot the new ToolStripControlHost into a specific place in an existing ToolStrip use the Insert method instead of Add This allows you to supply an index number for the position

Because the ToolStripControlHost.AutoSize property is set to true by default, the ToolStripItem automatically fits the exact size of the hosted control. Depending on the control you're hosting, you may need to set its BackgroundColor to Color.Transparent to make it look respectable. You may also need to set the AutoSize property to true to make sure its bounds are only as large as its content.

Figure 14-18 shows an example of a hosted control sandwiched between two ordinary buttons.

Ingresar Datetimepicker Toolstrip
Figure 14-18. A DateTimePicker in a ToolStrip

There are a few minor disadvantages to using the ToolStripControlHost:

• You can add only a single control. However, there's a workaround. If you want to place an arrangement with more than one control, you need to create a container control (like a Panel or UserControl) that has these controls. Then, use that container in the ToolStripControlHost.

• You need to create it and add the control to your ToolStrip programmatically because there's no design-time support. However, you can easily derive a custom ToolStripItem from ToolStripControlHost (as explained in the next section).

• You don't have strongly typed access to the hosted control. You need to cast the ToolStripControlHost.Control property to the right type to get access to control-specific members.

The ToolStripControlHost does one very smart thing—it provides numerous members that wrap basic properties and events from the Control class members. That means you can access properties like Text, Font, and ForeColor, and events like GotFocus, LostFocus, and KeyPress for the hosted control. If you need something more specific, you need to cast the Control property.

Here's an example of both approaches:

MessageBox.Show("The current date is " + item.Text); MessageBox.Show("The current date format is " + ((DateTimePicker)item.Control).Format.ToString());

.NET includes a rich set of controls that complement the ToolStrip. With the ToolStripControlHost you have the ability to use any control or combination of controls to create custom menu items, toolbar buttons, and tool windows.

0 0

Post a comment

  • Receive news updates via email from this site