c# - 如何使用集合编辑器窗口在 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();
}
}
}
解决方案
根据我的研究,如果我们想在设计中添加文本框,我们需要重写 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);
}
}
结果:(您需要手动设置文本框位置)
希望这可以帮助你。
推荐阅读
- r - 如果我知道 R 中的解和其他参数,如何求解交叉距离函数中的参数?
- node.js - 发布请求中的 req.body.rid 是什么意思?
- nestjs - 将 MongooseModule 添加到 AuthModule 后无法找出嵌套错误
- linux - 有没有办法一次比较 N 个文件,并且只保留每个文件唯一的行?
- php - php - 获取 pg_execute() 准备好的语句的关联数组返回 false
- android - 我正在编写 android 应用程序,但我无法发送 IR 密钥。这是我的代码。我不知道出了什么问题。我使用的是 android 9
- java - 在Android Studio Java中注册时如何根据该PhoneNumber检索uid
- c++ - std::vector 与按值传递的动态数组
- raspberry-pi - 树莓派摄像头模块产生无效图像
- firebase - 使用 Firebase Auth 自定义声明获取自定义权限