微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 用户控制停靠属性

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

解决方法

为了达到这个目的,你需要实现几个类;首先你需要一个自定义 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;
        }
    }
}

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.

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐