在实现了一个自定义控件后,如果希望在VS的界面编辑器中能对其进行操作,则必须对其添加Designer以及相应的属性:
[Designer(typeof(MyDesigner))]
[DesignTimeVisible(true)]public partial classUserControl1 : UserControl
{
……
[Browsable(false)] //在控件的属性设置列表中不可见
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]publicTabControl MyTabControl //用于Designer类中设置可编辑的子控件
{get{return this.tabControl1;
}
}
……
}internal classMyDesigner : ParentControlDesigner
{privateUserControl1 MyControl;public override voidInitialize(IComponent component)
{
……
MyControl = (UserControl1)component;
……
}
}
以上代码中,设计支持类MyDesigner 继承于ParentControlDesigner,表示该控件可以作为容器使用,这样就可以使得自定义控件成为容器。
如果不想让控件作为容器使用,而仅仅是需要在使用该控件的时候需要界面编辑器也能够操作UserControl中的控件,则继承ControlDesigner类即可。
为了让UserControl中的控件能够在设计器中也能够被操作,需要使用EnableDesignMode函数将控件设置为设计模式可编辑模式。
特别地,对于TabControl而言,还需要使用EnableDesignMode设置它的每一个TabPage,否则Tab页是无法添加控件的。
此外,TabControl只有在设计时新添加的TabPage才能够在上面添加控件,在UserControl中已经添加的虽然在设计器上可以添加控件,但是在设计器生成的代码中,并不会生成将控件添加到TabControl上的代码段,这事有点奇特,不知道是不是微软的BUG?
完整代码如下:
[Designer(typeof(MyDesigner))]
[DesignTimeVisible(true)]public partial classUserControl1 : UserControl
{publicUserControl1()
{
InitializeComponent();
}[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]publicTabControl MyTabControl
{get{return this.tabControl1;
}
}
}internal classMyDesigner : ParentControlDesigner
{privateUserControl1 MyControl;public override voidInitialize(IComponent component)
{base.Initialize(component);
MyControl=(UserControl1)component;bool succ = this.EnableDesignMode(MyControl.MyTabControl, "MyTabControl");foreach (TabPage item inMyControl.MyTabControl.TabPages)
{
succ=EnableDesignMode(item, item.Name);
}
}
}
Reference:



