根据上一篇《.NET创建宿主设计器--DesignHost、DesignSurface.》可以知道宿主容器在其中扮演着重要的角色。而DesignSurface就是宿主容器:他不仅仅是一个设计面,还提供了很多的服务,设计面+这些服务=宿主容器。
作为设计面
将他作为一个设计面是一个最重要的功能,可以通过下面的代码:
// 创建一个Form的设计面
DesignSurface ds = new DesignSurface();
ds.BeginLoad(typeof(Form));
//获得这个设计面的视图,并在一个窗体中显示出来(设计面也是一个Control)
Control c = ds.View as Control;
Form f = new Form();
c.Parent = f;
c.Dock = DockStyle.Fill;
f.Show();
如果我们想给设计面加菜单,或者工具条,可以通过加载服务的方式:
IServiceContainer container = ds .GetService(typeof(IServiceContainer)) as
IServiceContainer;
menuCommandService = new MenuCommandService(surface);
if (container != null)
{
container.AddService(typeof(IToolboxService), toolBoxService);
container.AddService(typeof(IMenuCommandService), menuCommandService);
}
这样,我们将ToolBox加到某种容器中(Panel)以后,便能够将工具箱和设计面关联起来了。
以某种状态加载设计器/保存设计器
我们可以将设计的页面保存为XML/C#/VB代码等,并且可以从这些代码文件中重新加载,并显示相应的定义设计器。这就是保存/加载设计器。
MS提供的主要有两个基础的设计器加载器(DesignerLoader):BasicDesignerLoade
CodeDomDesignerLoader。
这样我们就能通过某种加载器,序列化定义为相应的类型。(XML/C#/VB)
1.使用某种加载器:
DesignSurface ds = new DesignSurface();
BasicDesignerLoaderbasicHostLoader = new BasicDesignerLoader(typeof(Form));
hostSurface.BeginLoad(basicHostLoader);
hostSurface.Loader = basicHostLoader;
//获得这个设计面的视图,并在一个窗体中显示出来(设计面也是一个Control)
Control c = ds.View as Control;
Form f = new Form();
c.Parent = f;
c.Dock = DockStyle.Fill;
f.Show();
设计面上的创建组件
作为宿主容器还应该有创建组件的责任。并能够将这些组件绑定到设计面。这通过IDesignerHost 来实现,他提供设计器和对类型、服务和事务进行访问的主要接口,它还可用于创建和销毁组件。
如下代码所示:
IDesignerHost idh = (IDesignerHost)ds.GetService(typeof(IDesignerHost));
Button b = (Button)idh.CreateComponent(typeof(Button));// 创建组件
// Set the Parent of this Button to the RootComponent (the Form)
联系客服