如何使用集合编辑器窗口在 GroupBox 中创建 TextBox?

问题描述

我想创建一个自定义控件,该控件继承自 GroupBox 并具有一个作为 TextBox 集合的属性。我打算在设计器中创建任意数量的文本框,类似于 TabControl 可以完成的操作,可以通过集合编辑器窗口在 TabPages 属性中创建页面。 我创建了出现在属性窗口中的属性 TextBoxList,当我单击“...”集合编辑器窗口打开以创建文本框并设置其属性时,但是当我单击确定按钮时,没有文本框添加到我的 GroupBox。 TextBox 实例已创建,但未添加到 GroupBox。有人可以帮助我将 TextBox 添加到 GroupBox 吗?遵循代码

using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Forms;

namespace CustomizedControl
{
    public partial class GroupBoxWithTextBox : GroupBox
    {
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Editor(typeof(System.ComponentModel.Design.CollectionEditor),typeof(System.Drawing.Design.UITypeEditor))]
        [Description("The TextBoxes in GroupBox control."),Category("Behavior")]
        public Collection<TextBox> TextBoxList
        {
            get
            {
                return _textBoxList;
            }
        }
        private Collection<TextBox> _textBoxList = new Collection<TextBox>();

        public GroupBoxWithTextBox()
        {
            InitializeComponent();
        }
    }
}

解决方法

根据我的研究,如果我们想在设计中添加文本框,我们需要覆盖类 CollectionEditor。

我写了下面的代码,你可以看看。

代码:

[Serializable]
    public partial class GroupBoxWithTextBox : GroupBox
    {

        public GroupBoxWithTextBox()
        {
            SetStyle(ControlStyles.DoubleBuffer,true);
            SetStyle(ControlStyles.AllPaintingInWmPaint,true);
            Padding = new Padding(0);
            textBox = new TextBox();
            textBox.Size = new System.Drawing.Size(60,30);
            Controls1.Add(textBox);
            textBox.Dock = DockStyle.Top;
            
        }
        [EditorAttribute(typeof(NewCollectionEditor),typeof(System.Drawing.Design.UITypeEditor))]
        public   ControlCollection Controls1
        {
            get
            {
                return base.Controls;
            }
            set
            {
                
              
            }
        }


        private TextBox textBox;


     
    }

    public partial class NewCollectionEditor : CollectionEditor
    {
        public NewCollectionEditor(Type t) : base(t)
        {
        }

        // *** Magic happens here: ***
        // override the base class to SPECIFY the Type allowed
        // rather than letting it derive the Types from the collection type
        // which would allow any control to be added
        protected override Type[] CreateNewItemTypes()
        {
            Type[] ValidTypes = new[] { typeof(TextBox) };
            return ValidTypes;
        }

        public override object EditValue(ITypeDescriptorContext context,IServiceProvider provider,object value)
        {
            return base.EditValue(context,provider,value);
        }
    }

结果:(需要手动设置文本框位置)

希望能帮到你。

enter image description here