如果不知道什么是用户控件请搜索。如果不知道组件和控件的区别,请到论坛问。
最近在做一些组件的时候,希望能够像Tabcontrol那样的AddTab,RemoveTab的动作。
我个人觉得是设计自动化很重要的技术,所以我一直在寻找。很可惜的是,找到的多是辅助修改属性的东西,个人觉得没什么实际意义。动词对于开发组件和控件至关重要。
下面的例子是一个控件的,带有动词的,很好的例子。组件的相似,要简单些。读者阅读前需要了解Desiger的相关知识。不过复制代码,可以看看效果。我在VS2003上做的。
using System;
//using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.ComponentModel;
using System.Windows.Forms.Design;
using System.ComponentModel.Design;
namespace WindowsFormsApplication1
{
[Designer(typeof(DemoControlDesigner))]
public class DemoControl : Control
{
}
internal class DemoControlDesigner : ControlDesigner
{
public override DesignerVerbCollection Verbs
{
get
{
DesignerVerbCollection verbs = new DesignerVerbCollection();
verbs.Add(new DesignerVerb("Add a new Button", new EventHandler(AddNewButton)));
verbs.Add(new DesignerVerb("Remove an existed Button", new EventHandler(RemoveExistedButton)));
return verbs;
}
}
private void AddNewButton(object sender, EventArgs e)
{
Control ctrl = this.Control;
if (ctrl != null && ctrl.Parent != null)
{
IDesignerHost host = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
DesignerTransaction trans = host.CreateTransaction("Add a new button");
try
{
Control button = host.CreateComponent(typeof(Button)) as Control;
// other control initialization, must use ProeprtyDescriptor to set properties!
// Add to parent control's control collection.
PropertyDescriptor pd = TypeDescriptor.GetProperties(ctrl.Parent)["Controls"];
if (pd != null)
{
Control.ControlCollection cc = pd.GetValue(ctrl.Parent) as Control.ControlCollection;
if (cc != null)
{
cc.Add(button);
trans.Commit();
return;
}
}
trans.Cancel();
}
catch
{
trans.Cancel();
}
}
}
}
private void RemoveExistedButton(object sender, EventArgs e)
{
Control ctrl = this.Control;
if (ctrl != null && ctrl.Parent != null)
{
IDesignerHost host = this.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
DesignerTransaction trans = host.CreateTransaction("Remove an existed Button");
try
{
PropertyDescriptor pd = TypeDescriptor.GetProperties(ctrl.Parent)["Controls"];
if (pd != null)
{
Control.ControlCollection cc = pd.GetValue(ctrl.Parent) as Control.ControlCollection;
if (cc != null)
{
for (int i = cc.Count - 1; i >= 0; i--)
{
if(cc[i] is Button)
{
cc.RemoveAt(i);
trans.Commit();
return;
}
}
}
}
trans.Cancel();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
trans.Cancel();
}
}
}
}
}
}