Share via


Creating a strongly-typed wrapper for your ToolStripControlHost

The following sample shows how to wrap a TrackBar by inheriting from ToolStripControlHost. It is possible to just host the trackbar by these four lines of code:

TrackBar t = new TrackBar();
t.AutoSize = false; // the TrackBar wants to be 45px high by default, turning AutoSize = false fixes this
t.Height = 16;
toolStrip.Items.Add(new ToolStripControlHost(t));

However, if you want to use the TrackBar in the designer, you'll have to create a wrapper around the ToolStripControlHost class. The following sample shows how to wrap a property (TrackBar.Value), and an event (TrackBar.ValueChanged).

    [System.ComponentModel.DesignerCategory("code")]
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ToolStrip | ToolStripItemDesignerAvailability.StatusStrip)]
public partial class ToolStripTrackBar : ToolStripControlHost {
public ToolStripTrackBar() : base(CreateControlInstance()) {

}

        /// <summary>
/// Create a strongly typed property called TrackBar - handy to prevent casting everywhere.
/// </summary>
public TrackBar TrackBar {
get {
return Control as TrackBar;
}
}

        /// <summary>
/// Create the actual control, note this is static so it can be called from the
/// constructor.
///
/// </summary>
/// <returns></returns>
private static Control CreateControlInstance() {
TrackBar t = new TrackBar();
t.AutoSize = false;
t.Height = 16;

            // Add other initialization code here.
return t;
}

        [DefaultValue(0)]
public int Value {
get { return TrackBar.Value; }
set { TrackBar.Value = value; }
}

        /// <summary>
/// Attach to events we want to re-wrap
/// </summary>
/// <param name="control"></param>
protected override void OnSubscribeControlEvents(Control control) {
base.OnSubscribeControlEvents(control);
TrackBar trackBar = control as TrackBar;
trackBar.ValueChanged += new EventHandler(trackBar_ValueChanged);
}

        /// <summary>
/// Detach from events.
/// </summary>
/// <param name="control"></param>
protected override void OnUnsubscribeControlEvents(Control control) {
base.OnUnsubscribeControlEvents(control);
TrackBar trackBar = control as TrackBar;
trackBar.ValueChanged -= new EventHandler(trackBar_ValueChanged);

        }

        /// <summary>
/// Routing for event
/// TrackBar.ValueChanged -> ToolStripTrackBar.ValueChanged
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void trackBar_ValueChanged(object sender, EventArgs e) {
// when the trackbar value changes, fire an event.
if (this.ValueChanged != null) {
ValueChanged(sender, e);
}
}

        // add an event that is subscribable from the designer.
public event EventHandler ValueChanged;

        // set other defaults that are interesting
protected override Size DefaultSize {
get {
return new Size(200, 16);
}
}

}