使用 Visual C# 使 UserControl 对象充当控件容器设计时

本文介绍如何在设计时将 UserControl 对象添加到 Windows 窗体后,使 UserControl 对象充当控件容器。

原始产品版本: Visual C#
原始 KB 编号: 813450

总结

本文介绍Microsoft .NET Framework 类库命名空间 System.ComponentModel

本分步文章介绍了在将 UserControl 放在 Windows 窗体后,如何在设计时使 UserControl 对象充当控件容器。 在某些情况下,你可能想要将控件拖动到 UserControl。 为此,UserControl 必须充当控制容器。

默认情况下,UserControl 对象只能在创建控件时充当控件容器。 若要在将 UserControl 放在 Windows 窗体上后使 UserControl 托管构成控件,必须更改 UserControl 的默认设计器。 若要为组件实现设计时服务,请使用 DesignerAttribute 命名空间的 System.ComponentModel 类。 类 DesignerAttribute 声明之前。 DesignerAttribute通过传递designerTypeName参数和designerBaseType参数来初始化。

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

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

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

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

    1. 启动 Visual Studio。
    2. “文件” 菜单上,指向 “新建” ,然后单击 “项目”
    3. 在“项目类型”下,单击“Visual C#,然后单击“模板”下的“Windows 窗体控件库”。
  2. 将项目 命名为 ContainerUserControl。 默认情况下, 会创建UserControl1.cs

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

  4. 将以下代码添加到声明部分:

    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# 项目。 为此,请按照下列步骤进行操作:

    1. 启动 Visual Studio。
    2. “文件” 菜单上,指向 “新建” ,然后单击 “项目”
    3. 在“项目类型”下,单击“Visual C#,然后单击“模板”下的Windows 窗体应用程序 默认情况下, 会创建Form1.cs
  2. UserControl1 控件添加到工具箱。

    1. “工具” 菜单上,单击 “选择工具箱项”
    2. “.NET Framework 组件 ”选项卡上,单击“ 浏览”。
    3. “打开文件 ”框中,找到创建 UserControl 控件时生成的 DLL。
  3. 将 UserControl1 从工具箱(Windows 窗体)拖动到Form1.cs

  4. 将按钮控件从工具箱拖动到 UserControl1。

注意

UserControl1 的行为为 Button 控件的控件容器。

参考

有关详细信息,请参阅Microsoft网站: ParentControlDesigner 类