Ajuste de línea para una etiqueta en formularios de Windows


¿Cómo podemos obtener la funcionalidad de ajuste de línea para una etiqueta en Windows Forms?

Coloqué una etiqueta en un panel y agregué algo de texto para etiquetar dinámicamente. Pero excede la longitud del panel. ¿Cómo puedo resolver esto?

Author: Jim Fell, 2009-07-30

16 answers

La respuesta rápida: desactivar AutoSize .

El gran problema aquí es que la etiqueta no cambiará su altura automáticamente (solo ancho). Para hacer esto bien, necesitará subclasificar la etiqueta e incluir la lógica de redimensionamiento vertical.

Básicamente lo que necesitas hacer en OnPaint es:

  1. Mida la altura del texto (Gráficos.Measuremorstring).
  2. Si la altura de la etiqueta no es igual a la altura del texto, establezca la altura y devolver.
  3. Dibuja el texto.

También necesitará establecer la bandera de estilo ResizeRedraw en el constructor.

 141
Author: Jonathan C Dickinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-14 12:06:48

En realidad, la respuesta aceptada es innecesariamente complicada.

Si establece la etiqueta en tamaño automático, crecerá automáticamente con cualquier texto que ponga en ella. (Esto incluye el crecimiento vertical.)

Si desea que se ajuste a un ancho determinado, puede establecer la propiedad MaximumSize.

myLabel.MaximumSize = new Size(100, 0);
myLabel.AutoSize = true;

Probado y funciona.

 320
Author: John Gietzen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-05-25 15:00:26

En mi caso (etiqueta en un panel) pongo label.AutoSize = false y label.Dock = Fill. Y el texto de la etiqueta se envuelve automáticamente.

 19
Author: alex555,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-12 11:47:24

Malas noticias: no hay una propiedad autowrap.

Buenas noticias: ¡hay una luz al final del túnel!

Podría lograr esto programáticamente para dimensionarlo dinámicamente, pero aquí está la solución más fácil:

  • Seleccione las propiedades de la etiqueta
  • AutoSize = True
  • MaximumSize = (Width, Height ) donde Width = tamaño máximo que desea que sea la etiqueta y Height = cuántos píxeles desea que sea wrap

    Propiedades de la Muestra

 14
Author: Sebastian Castaldi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-10 08:21:27

Desde MSDN, Ajustar automáticamente el texto en la etiqueta:

using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing) 
            return;
        try {
            mGrowing = true;
            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height;
        }
        finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}
 11
Author: hypo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-14 12:08:58

Tuve que encontrar una solución rápida, así que solo usé un cuadro de texto con esas propiedades:

var myLabel = new TextBox
                    {
                        Text = "xxx xxx xxx",
                        WordWrap = true,
                        AutoSize = false,
                        Enabled = false,
                        Size = new Size(60, 30),
                        BorderStyle = BorderStyle.None,
                        Multiline =  true,
                        BackColor =  container.BackColor
                    };
 6
Author: user3356581,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-10 10:38:12

Tenga uno mejor basado en la respuesta de @hypo

public class GrowLabel : Label {
    private bool mGrowing;
    public GrowLabel() {
        this.AutoSize = false;
    }
    private void resizeLabel() {
        if (mGrowing)
            return;
        try {
            mGrowing = true;
            int width = this.Parent == null ? this.Width : this.Parent.Width;

            Size sz = new Size(this.Width, Int32.MaxValue);
            sz = TextRenderer.MeasureText(this.Text, this.Font, sz, TextFormatFlags.WordBreak);
            this.Height = sz.Height + Padding.Bottom + Padding.Top;
        } finally {
            mGrowing = false;
        }
    }
    protected override void OnTextChanged(EventArgs e) {
        base.OnTextChanged(e);
        resizeLabel();
    }
    protected override void OnFontChanged(EventArgs e) {
        base.OnFontChanged(e);
        resizeLabel();
    }
    protected override void OnSizeChanged(EventArgs e) {
        base.OnSizeChanged(e);
        resizeLabel();
    }
}

int width = this.Parent == null ? this.Width : this.Parent.Width; esto le permite usar auto-grow label cuando está acoplado a un padre, por ejemplo, un panel.

this.Height = sz.Height + Padding.Bottom + Padding.Top; aquí nos encargamos del relleno para la parte superior e inferior.

 3
Author: march1993,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-16 12:20:58
  1. Coloque la etiqueta dentro de un panel
  2. Manejar el ClientSizeChanged event para el panel, haciendo el etiqueta llenar el espacio:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Establezca Auto-Size para la etiqueta en true

  4. Establezca Dock para la etiqueta en Fill
 1
Author: noelicus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-26 15:20:35

No estoy seguro de que se ajuste a todos los casos de uso, pero a menudo uso un truco simple para obtener el comportamiento de envoltura: ponga su Label con AutoSize=false dentro de un 1x1 TableLayoutPanel que se encargará del tamaño del Label.

 1
Author: Pragmateek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-02 14:31:31

Establezca la propiedad AutoEllipsis en 'TRUE' y la propiedad AutoSize en 'FALSE'.

introduzca la descripción de la imagen aquí

introduzca la descripción de la imagen aquí

 1
Author: Ravi Kumar G N,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-27 06:19:34

Si su panel está limitando el ancho de su etiqueta, puede establecer la propiedad Anchor de su etiqueta en Left, Right y establecer AutoSize en true. Esto es conceptualmente similar a escuchar el evento SizeChanged del Panel y actualizar el tamaño máximo de la etiqueta a un new Size(((Control)sender).Size.Width, 0) como sugiere una respuesta anterior. Cada lado listado en la propiedad Anchor está, bien, anclado al lado interno respectivo del Control contenedor. Por lo tanto, enumerar dos lados opuestos en Anchor establece efectivamente la dimensión del control. Anchoring to Left and Right establece la propiedad Width del Control y Anchoring to Top and Bottom establecería su propiedad Height.

Esta solución, como C#:

label.Anchor = AnchorStyles.Left | AnchorStyles.Right;
label.AutoSize = true;
 0
Author: binki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:08

Si realmente quieres establecer el ancho de la etiqueta independiente del contenido, me parece que la forma más fácil es esta:

  • Establecer autosize true
  • Establezca el ancho máximo como lo desee
  • Establecer la anchura mínima de forma idéntica

Ahora la etiqueta es de ancho constante, pero adapta su altura automáticamente.

Luego, para el texto dinámico, disminuya el tamaño de la fuente. Si es necesario, use este fragmento en el sub donde se establece el texto de la etiqueta:

If Me.Size.Height - (Label12.Location.Y + Label12.Height) < 20 Then
    Dim naam As String = Label12.Font.Name
    Dim size As Single = Label12.Font.SizeInPoints - 1
    Label12.Font = New Font(naam, size)
End If
 0
Author: Kjell Verbeke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-14 14:19:34

Esto me ayudó en mi Forma llamada InpitWindow: En Diseñador para Etiqueta:

AutoSize = true;
Achors = Top, Left, Right.

private void InputWindow_Shown(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left - btOK.Margin.Right -
        lbCaption.Margin.Right - lbCaption.Margin.Left, 
        Screen.GetWorkingArea(this).Height / 2);
    this.Height = this.Height + (lbCaption.Height - btOK.Height - btCancel.Height);
    //Uncomment this line to prevent form height chage to values lower than initial height
    //this.MinimumSize = new Size(this.MinimumSize.Width, this.Height);
}
//Use this handler if you want your label change it size according to form clientsize.
private void InputWindow_ClientSizeChanged(object sender, EventArgs e) {
    lbCaption.MaximumSize = new Size(this.ClientSize.Width - btOK.Width - btOK.Margin.Left * 2 - btOK.Margin.Right * 2 -
        lbCaption.Margin.Right * 2 - lbCaption.Margin.Left * 2,
        Screen.GetWorkingArea(this).Height / 2);
}

Código completo de mi formulario

 0
Author: Mic,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-13 09:53:22

Si las dimensiones del botón deben mantenerse sin cambios:

myButton.Text = "word\r\nwrapped"
 0
Author: rjain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-01-06 16:10:06

La respuesta simple para este problema es cambiar la propiedad DOCK de la etiqueta. Es "NINGUNO" por defecto.

 0
Author: Sunil Neeradi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 11:26:54

Use style="overflow:Scroll" en la etiqueta como en el siguiente HTML. Esto agregará la barra de desplazamiento en la etiqueta dentro del panel.

<asp:Label
    ID="txtAOI"
    runat="server"
    style="overflow:Scroll"
    CssClass="areatext"
    BackColor="White"
    BorderColor="Gray"
    BorderWidth="1"
    Width = "900" ></asp:Label>
 -12
Author: Sweety Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-10 08:23:15