首页 > 解决方案 > 如何使用集合编辑器窗口在 GroupBox 中创建文本框?

问题描述

我想创建一个从 GroupBox 继承的自定义控件,并具有一个 TextBox 集合的属性。我打算在 Designer 中创建任意数量的 TextBox,与 TabControl 类似,可以通过 Collection Editor 窗口在 TabPages 属性中创建页面。我创建了出现在属性窗口中的属性 TextBoxList,当我单击“...”集合编辑器窗口打开以创建 TextBox 并设置其属性时,但是当我单击确定按钮时,没有一个 TextBox 被添加到我的 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();
        }
    }
}

标签: c#visual-studiowinformstextboxgroupbox

解决方案


根据我的研究,如果我们想在设计中添加文本框,我们需要重写 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);
        }
    }

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

希望这可以帮助你。

在此处输入图像描述


推荐阅读