C#中的自定义Windows控件库

4
我该如何在自己的自定义Windows控件库中实现小任务功能,就像下面这样的图片所示?
2个回答

4

您需要为自己的控件创建一个设计器。首先添加对System.Design的引用。示例控件可能如下所示:

using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;

[Designer(typeof(MyControlDesigner))]
public class MyControl : Control {
    public bool Prop { get; set; }
}

请注意[Designer]属性,它设置了自定义控件的设计器。为了开始使用您自己的设计器,请从ControlDesigner派生您自己的设计器。重写ActionLists属性以创建设计器的任务列表:

internal class MyControlDesigner : ControlDesigner {
    private DesignerActionListCollection actionLists;
    public override DesignerActionListCollection ActionLists {
        get {
            if (actionLists == null) {
                actionLists = new DesignerActionListCollection();
                actionLists.Add(new MyActionListItem(this));
            }
            return actionLists;
        }
    }
}

现在您需要创建自定义的ActionListItem,可能会像这样:
internal class MyActionListItem : DesignerActionList {
    public MyActionListItem(ControlDesigner owner)
        : base(owner.Component) {
    }
    public override DesignerActionItemCollection GetSortedActionItems() {
        var items = new DesignerActionItemCollection();
        items.Add(new DesignerActionTextItem("Hello world", "Category1"));
        items.Add(new DesignerActionPropertyItem("Checked", "Sample checked item"));
        return items;
    }
    public bool Checked {
        get { return ((MyControl)base.Component).Prop; }
        set { ((MyControl)base.Component).Prop = value; }
    }
}

在GetSortedActionItems方法中构建列表是创建自己的任务项面板的关键。

这是愉快的版本。我应该指出,在编写此示例代码时,我将Visual Studio崩溃到桌面三次。 VS2008对自定义设计器代码中未处理的异常不具有弹性。 经常保存。调试设计时代码需要启动另一个可以停止设计时异常的VS实例。


0

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