开发者

Custom Windows Control library in C#

H开发者_开发百科ow can I implement small task features in my own custom windows control library like below?

Custom Windows Control library in C#


You need to create your own designer for your control. Start that by adding a reference to System.Design. A sample control could look like this:

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

Note the [Designer] attribute, it sets the custom control designer. To get yours started, derive your own designer from ControlDesigner. Override the ActionLists property to create the task list for the designer:

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

Now you need to create your custom ActionListItem, that could look like this:

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

Building the list in the GetSortedActionItems method is the key to creating your own task item panel.

That's the happy version. I should note that I crashed Visual Studio to the desktop three times while working on this example code. VS2008 is not resilient to unhandled exceptions in the custom designer code. Save often. Debugging design time code requires starting another instance of VS that can stop the debugger on the design-time exceptions.


It's called a "Smart Tag". You can find a quick example of it here:

Adding Smart Tags to Windows Forms Controls
Source: How can I implement "small task features" in my own custom windows control library like below? - CodeProject
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜