[英]With a custom WinForms control, can I change the rectangle that nested controls dock inside?
我試圖創建一個自定義控件,其行為很像GroupBox
,但具有更改邊框顏色,更改組標簽文本顏色和隱藏組標簽的屬性。 控件直接從UserControl繼承,並覆蓋On_Paint以繪制邊框矩形以及表單設計者選擇的任何顏色的標簽。
我遇到的問題是在嘗試將嵌套控件停靠在其中時。 對接時,它使用控件的整個矩形,而不是繪制的矩形。 我希望它的行為類似於GroupBox,其中停靠控件僅限於控件邊框內的較小矩形。
是否有UserControl
的屬性(或者可能是Panel
,我可以繼承),允許您設置停靠嵌套控件停靠的矩形?
謝謝,Reza。 這正是我所需要的。 這是我的新控件,如果有人想使用它:
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
屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.