C# 用户控件停靠属性

C# 用户控件停靠属性,c#,winforms,user-controls,attributes,docking,C#,Winforms,User Controls,Attributes,Docking,我正在尝试制作自己的用户控件,并且几乎完成了,只是想添加一些润色。我希望设计器中的选项“停靠在父容器中”。有人知道怎么做吗?我找不到一个例子。我认为这与停靠属性有关。如果控件继承自UserControl(或大多数其他可用控件),则只需将Dock属性设置为DockStyle.Fill为了实现这一点,您需要实现几个类;首先你需要定制,然后你需要定制。两者都相当简单 ControlDesigner: public class MyUserControlDesigner : ControlDesigne

我正在尝试制作自己的用户控件,并且几乎完成了,只是想添加一些润色。我希望设计器中的选项“停靠在父容器中”。有人知道怎么做吗?我找不到一个例子。我认为这与停靠属性有关。

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

为了实现这一点,您需要实现几个类;首先你需要定制,然后你需要定制。两者都相当简单

ControlDesigner:

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;
        }
    }
}
DesignerActionList:

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
),并为该属性创建一个操作项。如果正在编辑的组件的
Dock
属性为
DockStyle.Fill
,则属性本身将返回
true
,否则
false
,如果
DockInParent
设置为
true
,则组件的
Dock
属性设置为
DockStyle.Fill
,否则
DockStyle.None


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

我还建议查看

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

此选项早在.NET 2.0中就可用,如果您只需要“在父容器中停靠/取消停靠”函数,则此选项要简单得多。在这种情况下,Designer类是一个巨大的滥杀滥伤

它还提供了
DockingBehavior.Never
DockingBehavior.AutoDock
选项
Never
不显示箭头并以默认的
Dock
行为加载新控件,而
AutoDock
显示箭头,但自动将控件作为
Fill
停靠

附言:很抱歉给一根线施了巫术。我正在寻找一个类似的解决方案,这是谷歌上出现的第一个问题。这个 设计师属性给了我一个想法,所以我开始四处挖掘 找到DockingAttribute,它似乎比公认的 具有相同请求结果的解决方案。希望这会有所帮助 未来的某个人


控件的Dock属性有什么问题?+1。对于像我这样正在研究自定义控件的设计时支持的人来说,你的文章非常棒。
[Docking(DockingBehavior.Ask)]
public class MyControl : UserControl
{
    public MyControl() { }
}