我正在尝试创建一个自定义控件,该控件的行为很像GroupBox
,但具有用于更改边框颜色,更改组标签文本颜色和隐藏组标签的属性。 该控件直接从 UserControl 继承,并重写On_Paint以使用窗体设计器选择的任何颜色绘制边框矩形和标签。
我遇到的问题是尝试将嵌套控件停靠在其中时。 停靠时,它使用控件的整个矩形,而不是绘制的矩形。 我希望它的行为类似于 GroupBox,其中停靠的控件仅限于控件边框内的较小矩形。
是否有 UserControl
的属性(或者可能是 Panel
,我可以继承它(允许您设置停靠嵌套控件停靠到的矩形?
谢谢你,礼萨。 这正是我所需要的。 这是我的新控件,如果有人想使用它:
public class LabelledPanel : Panel {
#region Constructors / Initializers
public LabelledPanel() : base() {
InitializeComponent();
}
private void InitializeComponent() {
this.BackColor = System.Drawing.Color.Transparent;
this.ForeColor = System.Drawing.Color.Red;
this.Name = "LabelledPanel";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
#region Private fields
private String text = "Label";
private Brush brush;
private Color foreColor;
private Boolean showLabel = true;
private Int32 labelHeight = 13;
private Int32 pad = 3;
#endregion
#region Properties
[Browsable(true)]
[Category("Appearance")]
public override String Text {
get { return text; }
set { text = value; }
}
[Browsable(true)]
[Category("Appearance")]
public override Color ForeColor {
get { return foreColor; }
set {
foreColor = value;
brush = new SolidBrush(value);
}
}
[Browsable(true)]
[Category("Layout")]
public Boolean ShowLabel {
get { return showLabel; }
set { showLabel = value; }
}
public override Rectangle DisplayRectangle {
get {
var r = GetBorderRect();
return new Rectangle(
r.Left + pad,
r.Top + pad,
r.Width - (2 * pad),
r.Height - (2 * pad));
}
}
#endregion
protected override void OnPaint(PaintEventArgs p) {
base.OnPaint(p);
ControlPaint.DrawBorder(p.Graphics, GetBorderRect(), foreColor, ButtonBorderStyle.Solid);
if (showLabel)
p.Graphics.DrawString(Text, Font, brush, 0, 0);
}
private Rectangle GetBorderRect() {
Rectangle r = this.ClientRectangle;
if (showLabel) {
r.Height -= labelHeight;
r.Y += labelHeight;
}
return r;
}
}
在停靠时控制其容器的DisplayRectangle
。
因此,您可以重写容器DisplayRectangle
属性,以通过停靠的子控件自定义填充区域。例如,您可以查看GroupBox
控件DisplayRectangle
属性的源代码。
此外,您可以设置Padding
属性,而不是重写显示矩形。对于容器控件,Padding
属性获取或设置其DisplayRectangle
属性。