新建一个继承自ToolboxService的类,名为DemoToolboxService,加上必要的using语句,在所继承的类名上按鼠标右键,点实现抽象类,已经帮我们自动完成了DemoToolboxService的框架,由于我们需要在设计器窗体上显示一个工具箱,就像VS左侧的那个工具面板,不过我们现在做一个简单一点的,就用ListBox,在DemoToolboxService中添加一个类型为ListBox的私有成员,并封装成属性。稍微改动一下,实现几个必要的方法,代码如下:
class DemoToolboxService : ToolboxService
{
private ListBox toolBox;
public ListBox ToolBox
{
get { return toolBox; }
set { toolBox = value; }
}
protected override CategoryNameCollection CategoryNames => null;
protected override string SelectedCategory
{
get => null;
set { }
}
//实现工具箱选择
protected override ToolboxItemContainer SelectedItemContainer
{
get
{
if (toolBox.SelectedIndex>0)
{
return new ToolboxItemContainer((ToolboxItem)toolBox.SelectedItem);
}
return null;
}
set
{
//实现鼠标画好控件后,让鼠标变回选择状态
if (value == null)
{
toolBox.SelectedIndex = -1;
}
}
}
//实现带分类的工具列表,由于目前不分类,所以即为全部工具
protected override IList GetItemContainers()
{
ToolboxItem[] t = new ToolboxItem[this.toolBox.Items.Count];
this.toolBox.Items.CopyTo(t, 0);
return t;
}
protected override IList GetItemContainers(string categoryName)
{
throw new NotImplementedException();
}
protected override void Refresh()
{
throw new NotImplementedException();
}
}
切换到主Form的设计界面,在那个SplitContainer左侧放上一个panel1,并把Dock属性设置为Left,作为将要完成的工具箱的容器,另外再放一个panel2,把Dock属性设置为Fill,作为Form的容器,再却换到Form的代码编辑界面,添加一个类型为DemoToolService的私有成员toolBoxService,修改Load事件代码,相关的代码如下:
public partial class Form1 : Form
{
private DemoToolboxService toolBoxService;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
DesignSurface surface = new DesignSurface();
surface.BeginLoad(typeof(Form));
Control view = (Control)surface.View;
view.Dock = DockStyle.Fill;
//原来的最后一行
//this.Controls.Add(view);
//this.splitContainer1.Panel1.Controls.Add(view);
this.panel2.Controls.Add(view);
this.propertyGrid1.SelectedObject = surface.ComponentContainer.Components[0];
toolBoxService = new DemoToolboxService();
toolBoxService.ToolBox = new ListBox();
toolBoxService.ToolBox.Items.Add("Point");
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(Button)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(TextBox)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(Label)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(TabControl)));
toolBoxService.ToolBox.Items.Add(new ToolboxItem(typeof(StatusBar)));
toolBoxService.ToolBox.Dock = DockStyle.Fill;
this.panel1.Controls.Add(toolBoxService.ToolBox);
//获取设计器的服务容器
IServiceContainer container = surface.GetService(typeof(IServiceContainer)) as IServiceContainer;
if (container != null)
{
//为对应的容器添加服务容器
container.AddService(typeof(IToolboxService), toolBoxService);
}
}
}
运行方案,并试着在所设计的窗体上加上几个控件,界面如下: