如果不知道什麼是使用者控制項請搜尋。如果不知道組件和控制項的區別,請到論壇問。
最近在做一些組件的時候,希望能夠像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();
}
}
}
}
}
}