用户控件停靠属性

5

我正在尝试制作自己的用户控件,已经快完成了,只是想要添加一些修饰。我希望在设计器中有一个选项可以“停靠在父容器”中。有人知道如何做到这一点吗?我找不到例子。我认为这与Docking属性有关。


1
控件的 Dock 属性出了什么问题? - tanascius
3个回答

16

我还建议查看DockingAttribute

[Docking(DockingBehavior.Ask)]
public class MyControl : UserControl
{
    public MyControl() { }
}

这也在控件的右上角显示“操作箭头”。

如果你只是想要“在父容器中停靠/脱离停靠”的功能,那么这个选项可以追溯到.NET 2.0,如果使用设计器类则会过于繁杂。

它还提供了DockingBehavior.NeverDockingBehavior.AutoDock两个选项。 Never不显示箭头,并将新控件加载为其默认Dock行为,而AutoDock显示箭头并自动将控件停靠为Fill

PS:抱歉打扰了一个旧帖子。我正在寻找类似的解决方案,这是谷歌上出现的第一件事。设计器属性给了我一个想法,所以我开始挖掘并发现了DockingAttribute,它与已接受的解决方案相比,可实现相同的请求结果,看望未来的某些人能从中受益。


6
为了实现这一点,您需要实现几个类;首先需要一个自定义的ControlDesigner,然后需要一个自定义的DesignerActionList。两者都相当简单。
控件设计器:
public class MyUserControlDesigner : ControlDesigner
{

    private DesignerActionListCollection _actionLists;
    public override System.ComponentModel.Design.DesignerActionListCollection ActionLists
    {
        get
        {
            if (_actionLists == null)
            {
                _actionLists = new DesignerActionListCollection();
                _actionLists.Add(new MyUserControlActionList(this));
            }
            return _actionLists;
        }
    }
}

设计者操作列表:
public class MyUserControlActionList : DesignerActionList
{
    public MyUserControlActionList(MyUserControlDesigner designer) : base(designer.Component) { }

    public override DesignerActionItemCollection GetSortedActionItems()
    {
        DesignerActionItemCollection items = new DesignerActionItemCollection();
        items.Add(new DesignerActionPropertyItem("DockInParent", "Dock in parent"));
        return items;
    }

    public bool DockInParent
    {
        get
        {
            return ((MyUserControl)base.Component).Dock == DockStyle.Fill;
        }
        set
        {
            TypeDescriptor.GetProperties(base.Component)["Dock"].SetValue(base.Component, value ? DockStyle.Fill : DockStyle.None);
        }
    }    
}

最后,您需要将设计器附加到您的控件:
[Designer("NamespaceName.MyUserControlDesigner, AssemblyContainingTheDesigner")]
public partial class MyUserControl : UserControl
{
    // all the code for your control

简要说明

该控件具有与之关联的Designer属性,指向我们的自定义设计器。该设计器中唯一的定制是暴露的DesignerActionList。它创建了我们自定义操作列表的实例,并将其添加到暴露的操作列表集合中。

自定义操作列表包含一个bool属性(DockInParent),并为该属性创建一个操作项。该属性本身将返回true,如果正在编辑的组件的Dock属性为DockStyle.Fill,否则返回false,如果DockInParent设置为true,则组件的Dock属性设置为DockStyle.Fill,否则设置为DockStyle.None

这将在设计器中显示控件右上角的小“操作箭头”,单击箭头将弹出任务菜单。


+1。你的帖子对于像我这样正在学习自定义控件设计时支持的人来说非常有用。 - Xam

4
如果您的控件继承自UserControl(或其他大多数可用控件),您只需要将Dock属性设置为DockStyle.Fill

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接