我有用户控件,其中包含一个名为“ToolbarButton”的对象列表。 ToolbarButton表示将添加到用户控件的用户按钮。
我的班级看起来像这样
public partial class Toolbar : UserControl
{
private MyCollection<ToolbarButton> _buttons = new MyCollection<ToolbarButton>();
public Toolbar()
{
InitializeComponent();
ToolbarCollectionEditor.toolbar = this;
}
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[Editor(typeof(ToolbarCollectionEditor),
typeof(System.Drawing.Design.UITypeEditor))]
public MyCollection<ToolbarButton> Buttons
{
get
{
return _buttons;
}
}
}
如您所见,我还实现了集合编辑器,以便我可以在设计时修改列表。
这一切都运行正常,我遇到的问题是在对列表进行更改时让控件重绘。我尝试添加一个事件来监听对象列表的更改(我的自定义列表类名为MyCollection),但因为CollectionEditor似乎只是重写了设计器代码而没有刷新它,所以它没有用。
谁能告诉我怎么做到这一点?最后,我希望能够单击Collection Editor中的Add按钮,让控件刷新并显示我添加的新按钮。
提前致谢!
更新
我创建了自己的CollectionEditor
class ToolbarCollectionEditor : CollectionEditor
{
public ToolbarCollectionEditor(Type type) : base(type) { }
public static Toolbar toolbar;
protected override CollectionForm CreateCollectionForm()
{
CollectionForm collectionForm = base.CreateCollectionForm();
collectionForm.FormClosed += new FormClosedEventHandler(collectionForm_FormClosed);
collectionForm.Load += new EventHandler(collectionForm_Load);
if (collectionForm.Controls.Count > 0)
{
TableLayoutPanel mainPanel = collectionForm.Controls[0]
as TableLayoutPanel;
if ((mainPanel != null) && (mainPanel.Controls.Count > 7))
{
// Get a reference to the inner PropertyGrid and hook
// an event handler to it.
PropertyGrid propertyGrid = mainPanel.Controls[5]
as PropertyGrid;
if (propertyGrid != null)
{
propertyGrid.PropertyValueChanged +=
new PropertyValueChangedEventHandler(
propertyGrid_PropertyValueChanged);
}
// Also hook to the Add/Remove
TableLayoutPanel buttonPanel = mainPanel.Controls[1]
as TableLayoutPanel;
if ((buttonPanel != null) && (buttonPanel.Controls.Count > 1))
{
Button addButton = buttonPanel.Controls[0] as Button;
if (addButton != null)
{
addButton.Click += new EventHandler(addButton_Click);
}
Button removeButton = buttonPanel.Controls[1] as Button;
if (removeButton != null)
{
removeButton.Click +=
new EventHandler(removeButton_Click);
}
}
}
}
return collectionForm;
}
private static void collectionForm_FormClosed(object sender,
FormClosedEventArgs e)
{
toolbar.RedrawButtons();
}
private static void collectionForm_Load(object sender, EventArgs e)
{
}
private static void propertyGrid_PropertyValueChanged(object sender,
PropertyValueChangedEventArgs e)
{
}
private static void addButton_Click(object sender, EventArgs e)
{
toolbar.RedrawButtons();
}
private static void removeButton_Click(object sender, EventArgs e)
{
toolbar.RedrawButtons();
}
}