將 TabControl 拖入設計器時,預設會加入兩個 TabPage。若繼承 TabControl 開發自訂控制項,這兩個預設頁籤常造成干擾。本文介紹透過自訂 ToolboxItem 移除預設 TabPage 的方法。
利用 [ToolboxItem] 屬性指定自訂 ToolboxItem 類別,覆寫 CreateComponentsCore 方法,在元件建立後移除預設頁籤。
[ToolboxItem(typeof(DemoToolboxItem))]
public class MyTabControl : TabControl
{
}
[Serializable]
class DemoToolboxItem : ToolboxItem
{
public DemoToolboxItem(Type toolType) : base(toolType) { }
protected DemoToolboxItem(SerializationInfo info, StreamingContext context)
{
Deserialize(info, context);
}
protected override IComponent[] CreateComponentsCore(IDesignerHost host, IDictionary defaultValues)
{
IComponent[] comps = base.CreateComponentsCore(host, defaultValues);
// 移除兩個預設 TabPage
((MyTabControl)comps[0]).TabPages.RemoveAt(0);
((MyTabControl)comps[0]).TabPages.RemoveAt(0);
return comps;
}
}
在 CreateComponentsCore 中亦可自行加入自訂 TabPage,賦予控制項更多實用預設值。