天天看点

HOW TO:使用 Visual C# .NET 使 UserControl 成为设计时控件容器

HOW TO:使用 Visual C# .NET 使 UserControl 成为设计时控件容器

概要

本分步指南介绍在将 UserControl 放在 Windows 窗体上之后,如何将 UserControl 对象用作设计时控件容器。可能会有这样的情况:您想将一个控件拖到 UserControl 中。为做到这一点, UserControl 必须用作控件容器。

概述

<script type="text/javascript"> loadTOCNode(2, 'summary'); </script>

默认情况下,UserControl 对象只有在您创建它时才可以用作控件容器。在将 UserControl 放在 Windows 窗体上之后,为让 UserControl 承载构成控件,您必须更改 UserControl 的默认设计器。如要为一个组件实现设计时服务,请使用 System.ComponentModel 名称空间的 DesignerAttribute 类。DesignerAttribute 出现在类声明前面。通过传递 designerTypeName 和 DesignerAttribute 参数初始化 designerTypeName。

designerTypeName 是提供设计时服务的设计器类型的完全合格的名称。传递 designerTypeName 参数的 System.Windows.Forms.Design.ParentControlDesigner 和 System.Design 的组合。ParentControlDesigner 类扩展了 UserControl 的设计时行为。

designerBaseType 是设计器的基类的名称。用于设计时服务的类必须实现 IDesigner 接口。

将 UserControl 创建为设计时控件容器

1. 创建一个新的 Visual C# .NET Windows 控件库项目。为此,请按照下列步骤操作:

a.启动 Visual Studio .NET。

b.在“文件”菜单上,指向“新建”,然后单击“项目”。

c.在“项目类型”下,单击 “Visual C# 项目”,然后单击“模板”下的 “Windows 控件库”。

2. 将该项目命名为 ContainerUserControl。默认情况下将创建出 “UserControl1.cs”。

3. 在解决方案资源管理器中,右键单击 “UserControl1.cs”,然后单击“查看代码”。

4. 将下面的代码添加到 Declarations 部分:

using System.ComponentModel.Design;

5. 如下所示将 System.ComponentModel.DesignerAttribute 属性应用到该控件:

[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]

public class UserControl1 :System.Windows.Forms.UserControl

{ ... }

6.在“生成”菜单上,单击“生成解决方案”。

测试 UserControl

1. 创建一个新的 Visual C# 项目。为此,请按照下列步骤操作:

a. 启动 Visual Studio .NET。

b. 在“文件”菜单上,指向“新建”,然后单击“项目”。

c. 在“项目类型”下,单击 “Visual C# 项目”,然后单击“模板”下的 “Windows 应用程序”。默认情况下将创建出 “Form1.cs”。

2. 将 “UserControl 1” 从工具箱(在“Windows 窗体”下)拖到 “Form1.cs”。

3. 将一个按钮控件从工具箱拖到 “UserControl 1” 。

4. 您会注意到 “UserControl 1” 起到了按钮控件的控件容器的作用。

继续阅读