WinForms自定义控件设计器:集合成员代码生成与持久化问题
自定义TableLayoutPanel控件设计器问题
我正在开发一个继承自TableLayoutPanel的自定义控件,搭配自定义设计器,将Label集合暴露到Visual Studio设计器的属性窗口中。
当前实现代码如下:
using Microsoft.DotNet.DesignTools.Designers; using System.CodeDom.Compiler; using System.Collections; using System.Collections.ObjectModel; using System.ComponentModel; namespace TestTableLayoutPanel { [Designer(typeof(TlpLabelsDesigner))] public partial class TlpLabels : TableLayoutPanel { public TlpLabels() { InitializeComponent(); } } public class TlpLabelsDesigner : ControlDesigner { public override void Initialize(IComponent component) { base.Initialize(component); labels.CollectionChanged += OnLabelsChanged; } private readonly ObservableCollection<Label> labels = new ObservableCollection<Label>(); public ObservableCollection<Label> Labels { get { return labels; } } private void OnLabelsChanged(object? sender, EventArgs e) { TableLayoutPanel tlp = (TableLayoutPanel)Control; tlp.RowStyles.Clear(); tlp.RowCount = Labels.Count; for(int i = 0; i < tlp.RowCount; i++) tlp.RowStyles.Add(new RowStyle(SizeType.Percent, 100.0F / tlp.RowCount)); for (int j = 0; j < tlp.RowCount; j++) { labels[j].Anchor = AnchorStyles.None; labels[j].TextAlign = ContentAlignment.MiddleCenter; tlp.Controls.Add(labels[j]); } } private readonly string[] RemovedProperties = new string[] { "Cell", "CellBorderStyle", "Column", "ColumnCount", "ColumnSpan", "GrowStyle", "Row", "RowCount", "RowSpan" }; protected override void PreFilterProperties(IDictionary properties) { foreach (string prop in RemovedProperties) properties.Remove(prop); string desc = "Auflistung aller Labels, die im TableLayoutPanel eingeordnet und angezeigt werden."; PropertyDescriptor pd = TypeDescriptor.CreateProperty(typeof(TlpLabelsDesigner), "Labels", typeof(ObservableCollection<Label>), new Attribute[] { new DesignOnlyAttribute(false), new BrowsableAttribute(true), new CategoryAttribute("Layout"), new DescriptionAttribute(desc)}); properties.Add("Labels", pd); base.PreFilterProperties(properties); } } }
遇到的问题:
- 打开集合编辑器添加Label时,初始化代码生成在
Form1.Designer.cs中,而非TlpLabels.Designer.cs; - 运行并关闭应用后再次打开集合编辑器,列表为空,但
Form1.Designer.cs中的初始化代码仍存在,且标签仍能在窗体中正常显示。
内容的提问来源于stack exchange,提问作者Flipps
相关产品推荐
相关产品推荐

