Center Header of a GroupBox

0

Can I somehow center the title (Header) of a GroupBox so that it is always established in the center of the control itself?

I do not know if there is any property that makes it easier for me to do what I want ... I'm reviewing the control options but I do not see anything that I'm worth.

With the property HorizontalAlignment="Center" I only get the control to adapt the content to what it has, but I want it to occupy the entire column of Grid containing it, always adapting to the maximum size of Grid

      <GroupBox Grid.Column="0" Header="GroupBox" HorizontalAlignment="Center">

I do not know if I'm explaining myself well ...

Thanks

    
asked by Edulon 10.12.2017 в 11:38
source

1 answer

1

You can extend the class GroupBox in the following way:

public class CustomGrpBox : GroupBox
{
    private string _Text = "";
    public CustomGrpBox()
    {
        //ponemos el texto base vacío
        base.Text = "";
    }
    //create a new property a
    [Browsable(true)]
    [Category("Appearance")]
    [DefaultValue("GroupBoxText")]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
    public new string Text
    {
        get
        {

            return _Text;
        }
        set
        {

            _Text = value;
            this.Invalidate();
        }
    }
    protected override void OnPaint(PaintEventArgs e)
    {

          //primero dejamos que la clase base dibuje el control
          base.OnPaint(e);
          //creamos un pincel con el color de la fuente
          SolidBrush colorBrush = new SolidBrush(this.ForeColor);
          //creamos un pincel con el color de fondo
          var backColor = new SolidBrush(this.BackColor);
          //mesuramos el tamaño del texto
          var size = TextRenderer.MeasureText(this.Text, this.Font);
          //evaluamos la posicion del texto de la izquierda
          int left = (this.Width - size.Width) / 2;
          //dibujamos un rectangulo de relleno para eliminar el borde
          e.Graphics.FillRectangle(backColor, new Rectangle(left, 0, size.Width, size.Height));
          //por último escrivimos el texto
          e.Graphics.DrawString(this.Text, this.Font, colorBrush, new PointF(left, 0));

    }
}

With the next extension of the class we are creating a control called CustomGroupBox , which you must use in the form to have the text centered.

    
answered by 11.12.2017 / 09:01
source