[WinForm] [UserControl] 自定义控件在界面编辑器中启用可视化编辑功能

在实现了一个自定义控件后,如果希望在VS的界面编辑器中能对其进行操作,则必须对其添加Designer以及相应的属性:

[Designer(typeof(MyDesigner))]
[DesignTimeVisible(true)]
public partial class UserControl1 : UserControl
{
    ……
    [Browsable(false)]                //在控件的属性设置列表中不可见
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public TabControl MyTabControl    //用于Designer类中设置可编辑的子控件
    {
        get
        {
            return this.tabControl1;
        }
    }
    ……
}

internal class MyDesigner : ParentControlDesigner
{
    private UserControl1 MyControl;

    public override void Initialize(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 class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    [Browsable(false)]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public TabControl MyTabControl
    {
        get
        {
            return this.tabControl1;
        }
    }
}
internal class MyDesigner : ParentControlDesigner
{
    private UserControl1 MyControl;

    public override void Initialize(IComponent component)
    {
        base.Initialize(component);

        MyControl = (UserControl1)component;

        bool succ = this.EnableDesignMode(MyControl.MyTabControl, "MyTabControl");
        foreach (TabPage item in MyControl.MyTabControl.TabPages)
        {
            succ = EnableDesignMode(item, item.Name);
        }
    }
}

 

 

 

 

 

Reference:

http://stackoverflow.com/questions/8186053/how-do-i-provide-designer-support-to-a-tabcontrol-residing-in-a-usercontrol-so

posted @ 2012-06-01 10:18  BlueGlass  阅读(3022)  评论(0编辑  收藏  举报