Custom Control Not Playing Nice With PropertyGrid
I have a class that is implementing a custom ToolStripItem. Everything seems to work great until I try to add the item to a ContextMenuStrip at design time. If I try to add my custom control straight from the ContextMenuStrip the PropertyGrid freezes up and will not let me modify my Checked or Text properties. But if I go into the ContextMenuStrip PropertyGrid and add my custom control through the Items(...)
property, I can modify the custom control just fine within that dialog. I'm not sure if I'm missing an attribute somewhere of if its a problem with the underlying code. Here is a copy of the CustomToolStripItem class. As you can see, its a very simple class.
[ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip)]
public class CustomToolStripItem : ToolStripControlHost {
#region Public Properties
[Description("Gets or sets a value indicating whether the object is in the checked state")]
[ReadOnly(false)]
public bool Checked { get { return checkBox.Checked; } set { checkBox.Checked = value; } }
[Description("开发者_Python百科Gets or sets the object's text")]
[ReadOnly(false)]
public override string Text { get { return checkBox.Text; } set { checkBox.Text = value; } }
#endregion Public Properties
#region Public Events
public event EventHandler CheckedChanged;
#endregion Public Events
#region Constructors
public CustomToolStripItem()
: base(new FlowLayoutPanel()) {
// Setup the FlowLayoutPanel.
controlPanel = (FlowLayoutPanel)base.Control;
controlPanel.BackColor = Color.Transparent;
// Add the child controls.
checkBox.AutoSize = true;
controlPanel.Controls.Add(checkBox);
}
#endregion Constructors
#region Protected Methods
protected override void OnSubscribeControlEvents(Control control) {
base.OnSubscribeControlEvents(control);
checkBox.CheckedChanged += new EventHandler(CheckChanged);
}
protected override void OnUnsubscribeControlEvents(Control control) {
base.OnUnsubscribeControlEvents(control);
checkBox.CheckedChanged -= new EventHandler(CheckChanged);
}
#endregion Protected Methods
#region Private Methods
private void CheckChanged(object sender, EventArgs e) {
// Throw the CustomToolStripItem's CheckedChanged event
EventHandler handler = CheckedChanged;
if (handler != null) { handler(sender, e); }
}
#endregion Private Methods
#region Private Fields
private FlowLayoutPanel controlPanel;
private CheckBox checkBox = new CheckBox();
#endregion Private Fields
If you don't mind using the standard ToolStripMenuItem it should have all the functionality of the custom control you created. It has both "Text" and "Checked" properties and event handlers already, plus all the normal bells and whistles, although the "checked" look for a ToolStripMenuItem is different from a regular check box.
精彩评论