本分步指南介紹在將 UserControl 放在 Windows 窗體上之后,如何將 UserControl 對象用作設計時控件容器。可能會有這樣的情況:您想將一個控件拖到 UserControl 中。為做到這一點, UserControl 必須用作控件容器。
概述
默認情況下,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 創建為設計時控件容器
- 創建一個新的 Visual C# .NET Windows 控件庫項目。為此,請按照下列步驟操作:
- 啟動 Visual Studio .NET。
- 在“文件”菜單上,指向“新建”,然后單擊“項目”。
- 在“項目類型”下,單擊 “Visual C# 項目”,然后單擊“模板”下的 “Windows 控件庫”。
- 將該項目命名為 ContainerUserControl。默認情況下將創建出 “UserControl1.cs”。
- 在解決方案資源管理器中,右鍵單擊 “UserControl1.cs”,然后單擊“查看代碼”。
- 將下面的代碼添加到 Declarations 部分:
using System.ComponentModel.Design;
- 如下所示將 System.ComponentModel.DesignerAttribute 屬性應用到該控件:
[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))] public class UserControl1 :System.Windows.Forms.UserControl { ... }
- 在“生成”菜單上,單擊“生成解決方案”。
測試 UserControl
- 創建一個新的 Visual C# 項目。為此,請按照下列步驟操作:
- 啟動 Visual Studio .NET。
- 在“文件”菜單上,指向“新建”,然后單擊“項目”。
- 在“項目類型”下,單擊 “Visual C# 項目”,然后單擊“模板”下的 “Windows 應用程序”。默認情況下將創建出 “Form1.cs”。
- 將 “UserControl1” 從工具箱(在“Windows 窗體”下)拖到 “Form1.cs”。
- 將一個按鈕控件從工具箱拖到 “UserControl1”。
- 您會注意到 “UserControl1” 起到了按鈕控件的控件容器的作用。