C# C语言中的自定义Windows控件库#
如何在我自己的自定义windows控件库(如下所示)中实现小任务功能?C# C语言中的自定义Windows控件库#,c#,custom-controls,C#,Custom Controls,如何在我自己的自定义windows控件库(如下所示)中实现小任务功能? 您需要为控件创建自己的设计器。首先添加对System.Design的引用。示例控件可以如下所示: using System; using System.Windows.Forms; using System.ComponentModel; using System.ComponentModel.Design; using System.Windows.Forms.Design; [Designer(typeof(MyCon
您需要为控件创建自己的设计器。首先添加对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; }
}
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; }
}
}
注意[Designer]属性,它设置自定义控件设计器。要开始,请从ControlDesigner派生您自己的设计器。重写ActionList属性以创建设计器的任务列表:
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,如下所示:
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; }
}
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方法中构建列表是创建自己的任务项面板的关键
这是快乐的版本。我应该注意到,在处理这个示例代码时,我曾三次将VisualStudio死机到桌面上。VS2008对自定义设计器代码中未处理的异常没有弹性。经常储蓄。调试设计时代码需要启动另一个VS实例,该实例可以在设计时异常时停止调试器。它被称为“智能标记”。您可以在此处找到一个快速示例:
资料来源: