我正在尝试扩展TextBox以在其左侧添加一个Label并将其视为一个Control,因此我不必跟踪它们的大小,位置等.
我创建了一个TextBoxWithLabel类,它扩展了Control并具有TextBox和Label字段,但我不确定要为onPaint()做什么 - 我是否必须告诉它手动绘制两个项目?如果是这样,怎么样?我猜测默认继承的行为不会到'检查我是否包含任何子控件,如果我这样做,请绘制它们'...
这甚至是最好的方法吗?我以前让我的类扩展TextBox并添加了Label字段,但当然没有添加到包含TextBoxWithLabel的Panel中,因此没有绘制.
任何有正确方向的建议或捅都会受到赞赏.
谢谢,
亚历克斯
这里的典型方法是UserControl,您可以在其中放置标签和文本框.但是很痛苦,你必须向用户控件添加文本框的很多属性和事件,这样它至少类似于文本框.丑陋的样板代码.
另一种方法是创建一个隐藏在父级标签控件中的自定义文本框.这完全像TextBox一样,无需做任何工作.在项目中添加一个新类并粘贴下面显示的代码.编译.将新控件从工具箱顶部拖放到表单上.将Description属性设置为要在标签中显示的文本.
using System;
using System.Drawing;
using System.Windows.Forms;
class MyTextBox : TextBox {
private Label label;
public MyTextBox() {
label = new Label();
label.AutoSize = true;
label.Font = this.Font;
label.Location = this.Location;
label.Resize += new EventHandler(label_Resize);
}
protected override void OnParentChanged(EventArgs e) {
// Keeps label on the same parent as the text box
base.OnParentChanged(e);
label.Parent = this.Parent; // NOTE: no dispose necessary
}
private void moveLabel() {
// Keep label right-aligned to the left of the text box
label.Location = new Point(this.Left - label.Width - 10, this.Top);
}
private void label_Resize(object sender, EventArgs e) {
moveLabel();
}
protected override void OnLocationChanged(EventArgs e) {
base.OnLocationChanged(e);
moveLabel();
}
public string Description {
get { return label.Text; }
set { label.Text = value; }
}
public override Font Font {
get { return base.Font; }
set { base.Font = label.Font = value; }
}
}
Run Code Online (Sandbox Code Playgroud)