把TabControl添加到設(shè)計器的時候,默認會添加兩個TabPage,當(dāng)繼承TabControl自定義控件的時候,這兩個默認的TabPage常常會制造一些麻煩,今天我來介紹一種方法來去掉這兩個默認的TabPage:
實際上思路比較簡單,主要是通過ToolboxItem特性提供自定義的ToolboxItem類來修改工具箱中的控件的初始化工程,只需要繼承ToolboxItem類,重寫CreateComponentsCore方法就可以實現(xiàn)了:
[ToolboxItem(typeof(DemoToolboxItem))]
public class MyTabControl : TabControl
{
}
[Serializable] //ToolboxItem必須是可序列化的
class DemoToolboxItem : ToolboxItem
{
// The add components dialog in VS looks for a public
// ctor that takes a type.
public DemoToolboxItem(Type toolType)
: base(toolType)
{
}
// And you must provide this special constructor for serialization.
// If you add additional data to MyToolboxItem that you
// want to serialize, you may override Deserialize and
// Serialize methods to add that data.
DemoToolboxItem(SerializationInfo info, StreamingContext context)
{
Deserialize(info, context);
}
// This implementation sets the new control's Text and
// AutoSize properties.
protected override IComponent[] CreateComponentsCore(
IDesignerHost host,
IDictionary defaultValues)
{
IComponent[] comps = base.CreateComponentsCore(host, defaultValues);
MessageBox.Show(((MyTabControl)comps[0]).TabPages.Count.ToString());
((MyTabControl)comps[0]).TabPages.RemoveAt(0);//去掉默認添加的TabPage
((MyTabControl)comps[0]).TabPages.RemoveAt(0);
return comps;
}
}
當(dāng)然,如果愿意的話,也可以自己在CreateComponentsCore中添加自定義的TabPage來使我們的TabControl更加的有實用價值!