[WinForm] [UserControl] 自定义控件在界面编辑器中启用可视化编辑功能
在实现了一个自定义控件后,如果希望在VS的界面编辑器中能对其进行操作,则必须对其添加Designer以及相应的属性:
[Designer(typeof(MyDesigner))] [DesignTimeVisible(true)] public partial class UserControl1 : UserControl { …… [Browsable(false)] //在控件的属性设置列表中不可见 [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TabControl MyTabControl //用于Designer类中设置可编辑的子控件 { get { return this.tabControl1; } } …… } internal class MyDesigner : ParentControlDesigner { private UserControl1 MyControl; public override void Initialize(IComponent component) {
……
MyControl = (UserControl1)component;
……
}
}
以上代码中,设计支持类MyDesigner 继承于ParentControlDesigner,表示该控件可以作为容器使用,这样就可以使得自定义控件成为容器。
如果不想让控件作为容器使用,而仅仅是需要在使用该控件的时候需要界面编辑器也能够操作UserControl中的控件,则继承ControlDesigner类即可。
为了让UserControl中的控件能够在设计器中也能够被操作,需要使用EnableDesignMode函数将控件设置为设计模式可编辑模式。
特别地,对于TabControl而言,还需要使用EnableDesignMode设置它的每一个TabPage,否则Tab页是无法添加控件的。
此外,TabControl只有在设计时新添加的TabPage才能够在上面添加控件,在UserControl中已经添加的虽然在设计器上可以添加控件,但是在设计器生成的代码中,并不会生成将控件添加到TabControl上的代码段,这事有点奇特,不知道是不是微软的BUG?
完整代码如下:
[Designer(typeof(MyDesigner))] [DesignTimeVisible(true)] public partial class UserControl1 : UserControl { public UserControl1() { InitializeComponent(); } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TabControl MyTabControl { get { return this.tabControl1; } } } internal class MyDesigner : ParentControlDesigner { private UserControl1 MyControl; public override void Initialize(IComponent component) { base.Initialize(component); MyControl = (UserControl1)component; bool succ = this.EnableDesignMode(MyControl.MyTabControl, "MyTabControl"); foreach (TabPage item in MyControl.MyTabControl.TabPages) { succ = EnableDesignMode(item, item.Name); } } }
Reference:
分类:
C#
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程