【问题标题】:With a custom WinForms control, can I change the rectangle that nested controls dock inside?使用自定义 WinForms 控件,我可以更改嵌套控件停靠在里面的矩形吗?
【发布时间】:2016-02-17 19:01:57
【问题描述】:

我正在尝试创建一个行为类似于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;
    }
}

【问题讨论】:

  • 顺便说一句,最好不要将答案作为问题的一部分发布。这可能会让未来的读者感到困惑。您可以发布已编辑的部分作为答案。

标签: .net winforms docking


【解决方案1】:

在停靠时控制其容器的DisplayRectangle
因此,您可以覆盖容器的DisplayRectangle 属性,以通过停靠的子控件自定义填充区域。例如,您可以查看GroupBox控件的DisplayRectangle属性的源代码。

您也可以设置Padding 属性,而不是覆盖显示矩形。对于容器控件,Padding 属性获取或设置它们的DisplayRectangle 属性。

【讨论】:

    猜你喜欢
    • 2013-03-08
    • 2012-04-10
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多