用户控制停靠属性

Pet*_*teT 4 c# user-controls attributes docking winforms

我试图让我自己的用户控制并几乎完成它,只是试图添加一些抛光.我希望设计器中的选项"Dock in parent container".有谁知道如何做到这一点我找不到一个例子.我认为它与Docking Attribute有关.

Sty*_*ver 16

我还建议查看DockingAttribute.

[Docking(DockingBehavior.Ask)]
public class MyControl : UserControl
{
    public MyControl() { }
}
Run Code Online (Sandbox Code Playgroud)

这也会在控件的右上角显示"操作箭头".

这个选项早在.NET 2.0就可以使用了,如果您所寻找的只是'父容器中的Dock/Undock'功能,它就更简单了.在这种情况下,Designer类是非常矫枉过正的.

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

PS:很抱歉有一个线程坏死.我一直在寻找类似的解决方案,这是谷歌首次出现的问题.Designer属性给了我一个想法,所以我开始挖掘并找到了DockingAttribute,它似乎比公认的解决方案更清晰,具有相同的请求结果.希望这将有助于未来的人.


Fre*_*örk 6

为了达到这个目的,你需要实现几个类; 首先,您需要一个自定义ControlDesigner,然后您将需要一个自定义DesignerActionList.两者都相当简单.

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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);
        }
    }    
}
Run Code Online (Sandbox Code Playgroud)

最后,您需要将设计师附加到您的控件:

[Designer("NamespaceName.MyUserControlDesigner, AssemblyContainingTheDesigner")]
public partial class MyUserControl : UserControl
{
    // all the code for your control
Run Code Online (Sandbox Code Playgroud)

简要说明

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

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

这将在设计器中显示靠近控件右上角的小"动作箭头",然后单击箭头将弹出任务菜单.