Alineación vertical de texto en WPF TextBlock


¿Cómo puedo asignar la alineación central vertical al texto dentro de un TextBlock? He encontrado la propiedad textAlignment pero es para la alineación horizontal del texto. ¿Cómo lo hago para la alineación vertical de texto?

Author: Adam K Dean, 2009-09-29

16 answers

Un Textblock no puede hacer alineación vertical

La mejor manera de hacer esto que he encontrado es poner el textblock dentro de un borde, para que el borde haga la alineación por usted.

<Border BorderBrush="{x:Null}" Height="50">
    <TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>

Nota: Esto es funcionalmente equivalente al uso de una cuadrícula, solo depende de cómo desea que los controles encajen con el resto de su diseño en cuanto a cuál es más adecuado

 240
Author: Orion Edwards,
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
2010-04-13 23:20:52

Mientras que La respuesta de Orion Edwards funciona para cualquier situación, puede ser una molestia agregar el borde y establecer las propiedades del borde cada vez que desee hacer esto. Otra forma rápida es establecer el relleno del bloque de texto:

<TextBlock Height="22" Padding="3" />
 83
Author: Ben Jones,
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 11:55:10

El TextBlock no admite la alineación vertical de texto.

Trabajo alrededor de esto envolviendo el bloque de texto con una Cuadrícula y estableciendo HorizontalAlignment="Stretch" y VerticalAlignment="Center".

Así:

    <Grid>
        <TextBlock 
            HorizontalAlignment="Stretch"
            VerticalAlignment="Center"
            Text="Your text" />
    </Grid>
 47
Author: hwiechers,
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
2009-10-28 05:39:40

Puede usar label en lugar de textblock.

<Label Content="Hello, World!">
    <Label.LayoutTransform>
        <RotateTransform Angle="270"/>
    </Label.LayoutTransform>
</Label>
 15
Author: Aneesh Daniel,
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-08-22 10:01:18

Si puede prescindir del ajuste de texto, creo que reemplazar el TextBlock con una etiqueta es la forma más sucinta de hacer esto. De lo contrario, siga una de las otras respuestas válidas.

<Label Content="Some Text" VerticalAlignment="Center"/>
 2
Author: Mike Fuchs,
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:35

Para mí, VerticalAlignment="Center" soluciona este problema.
Esto podría deberse a que TextBlock está envuelto en una cuadrícula, pero entonces también lo está prácticamente todo en wpf.

 1
Author: user448777,
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-08-28 20:03:56

He encontrado que modificar el estilo del cuadro de texto (es decir: controltemplate) y luego modificar la PART_ContentHost alineación vertical al Centro hará el truco

 1
Author: JLuis Estrada,
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-11-25 20:46:34

Solo para reírse, dale un giro a este XAML. No es perfecto, ya que no es una 'alineación', pero le permite ajustar la alineación del texto dentro de un párrafo.

<TextBlock>
    <TextBlock BaselineOffset="30">One</TextBlock>
    <TextBlock BaselineOffset="20">Two</TextBlock>  
    <Run>Three</Run>            
    <Run BaselineAlignment="Subscript">Four</Run>   
</TextBlock>
 1
Author: Gusdor,
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
2012-07-18 10:46:33

Si puedes pasar por alto la altura de TextBlock, es mejor que uses esto:

<TextBlock Height="{Binding}" Text="Your text"
TextWrapping="Wrap" VerticalAlignment="Center" Width="28"/>
 1
Author: fa wildchild,
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
2012-08-07 15:30:24

En mi caso, hice esto para hacer que la pantalla TextBlock sea más agradable.

<Border BorderThickness="3" BorderBrush="Yellow" CornerRadius="10" Padding="2"
    HorizontalAlignment="Center" VerticalAlignment="Center" Height="30" Width="150">
        <TextBlock FontSize="20" Height="23" HorizontalAlignment="Left" Margin="0,0,0,-5" Text="" VerticalAlignment="Top" Width="141" Background="White" />
</Border>

El truco para hacer el texto más lejos de la parte inferior es establecer

Margin="0,0,0,-5"
 1
Author: Brandon Gao,
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
2012-09-25 22:03:33

Encontré que tenía que hacerlo un poco diferente. Mi problema era que si cambiaba el tamaño de la fuente, el texto se movería hacia arriba en el cuadro de texto en lugar de permanecer en la parte inferior con el resto de cuadros de texto en la línea. Al cambiar la alineación vert de arriba a abajo, pude cambiar la fuente programáticamente de tamaño 20 a tamaño 14 y atrás, manteniendo la gravedad del texto en la parte inferior y manteniendo las cosas ordenadas. He aquí cómo:

introduzca la descripción de la imagen aquí

 1
Author: Dave S.,
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-08-10 02:58:22

Cuadro de texto alineado verticalmente de una sola línea.

Para ampliar la respuesta proporcionada por @Orion Edwards, así es como lo haría completamente desde código detrás (sin estilos establecidos). Básicamente cree una clase personalizada que hereda de Border que tiene su Hijo establecido en un cuadro de texto. El siguiente ejemplo asume que solo desea una sola línea y que el borde es un hijo de un lienzo. También asume que necesitaría ajustar la propiedad MaxLength del cuadro de texto en función del ancho del borde. El ejemplo a continuación también establece el cursor de la Borde para imitar un cuadro de texto configurándolo al tipo 'iBeam'. Se establece un margen de ' 3 ' para que el cuadro de texto no esté absolutamente alineado a la izquierda del borde.

double __dX = 20;
double __dY = 180;
double __dW = 500;
double __dH = 40;
int __iMaxLen = 100;

this.m_Z3r0_TextBox_Description = new CZ3r0_TextBox(__dX, __dY, __dW, __dH, __iMaxLen, TextAlignment.Left);
this.Children.Add(this.m_Z3r0_TextBox_Description);

Clase:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;


namespace ifn0tz3r0Exp
{
    class CZ3r0_TextBox : Border
    {
        private TextBox m_TextBox;

        private SolidColorBrush m_Brush_Green = new SolidColorBrush(Colors.MediumSpringGreen);
        private SolidColorBrush m_Brush_Black = new SolidColorBrush(Colors.Black);
        private SolidColorBrush m_Brush_Transparent = new SolidColorBrush(Colors.Transparent);

        public CZ3r0_TextBox(double _dX, double _dY, double _dW, double _dH, int _iMaxLen, TextAlignment _Align)
        {

            /////////////////////////////////////////////////////////////
            //TEXTBOX
            this.m_TextBox = new TextBox();
            this.m_TextBox.Text = "This is a vertically centered one-line textbox embedded in a border...";
            Canvas.SetLeft(this, _dX);
            Canvas.SetTop(this, _dY);
            this.m_TextBox.FontFamily = new FontFamily("Consolas");
            this.m_TextBox.FontSize = 11;
            this.m_TextBox.Background = this.m_Brush_Black;
            this.m_TextBox.Foreground = this.m_Brush_Green;
            this.m_TextBox.BorderBrush = this.m_Brush_Transparent;
            this.m_TextBox.BorderThickness = new Thickness(0.0);
            this.m_TextBox.Width = _dW;
            this.m_TextBox.MaxLength = _iMaxLen;
            this.m_TextBox.TextAlignment = _Align;
            this.m_TextBox.VerticalAlignment = System.Windows.VerticalAlignment.Center;
            this.m_TextBox.FocusVisualStyle = null;
            this.m_TextBox.Margin = new Thickness(3.0);
            this.m_TextBox.CaretBrush = this.m_Brush_Green;
            this.m_TextBox.SelectionBrush = this.m_Brush_Green;
            this.m_TextBox.SelectionOpacity = 0.3;

            this.m_TextBox.GotFocus += this.CZ3r0_TextBox_GotFocus;
            this.m_TextBox.LostFocus += this.CZ3r0_TextBox_LostFocus;
            /////////////////////////////////////////////////////////////
            //BORDER

            this.BorderBrush = this.m_Brush_Transparent;
            this.BorderThickness = new Thickness(1.0);
            this.Background = this.m_Brush_Black;            
            this.Height = _dH;
            this.Child = this.m_TextBox;
            this.FocusVisualStyle = null;
            this.MouseDown += this.CZ3r0_TextBox_MouseDown;
            this.Cursor = Cursors.IBeam;
            /////////////////////////////////////////////////////////////
        }
        private void CZ3r0_TextBox_MouseDown(object _Sender, MouseEventArgs e)
        {
            this.m_TextBox.Focus();
        }
        private void CZ3r0_TextBox_GotFocus(object _Sender, RoutedEventArgs e)
        {
            this.BorderBrush = this.m_Brush_Green;
        }
        private void CZ3r0_TextBox_LostFocus(object _Sender, RoutedEventArgs e)
        {
            this.BorderBrush = this.m_Brush_Transparent;
        }
    }
}
 1
Author: Aaron,
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-09-08 16:47:33

Puedes ver mi entrada de blog. Puede establecer la altura personalizada de Textblock desde codebehind. Para configurar la altura personalizada, debe configurarla dentro de un borde o un panel apilable

Http://ciintelligence.blogspot.com/2011/02/wpf-textblock-vertical-alignment-with.html

 0
Author: Syed Bashar,
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-08-16 17:55:43

Creo que es mejor usar una Etiqueta (o TextBlock) en una Etiqueta, no se puede adjuntar un evento de ratón directamente en el control fronterizo, finalmente se adjunta en el TextBlock, esta es mi recomendación:

<Label 
    Height="32"
    VerticalContentAlignment="Center"
    HorizontalContentAlignment="Stretch"
    MouseLeftButtonUp="MenuItem_MouseLeftButtonUp">
    <TextBlock Padding="32 0 10 0">
        Label with click event
    </TextBlock>
</Label>
 0
Author: acamro,
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-11-20 03:21:33
  <TextBox AcceptsReturn="True" 
           TextWrapping="Wrap"  
           VerticalContentAlignment="Top" >
  </TextBox>
 0
Author: Bastianon Massimo,
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-16 17:11:58

TextBlock no admite la alineación vertical de su contenido. Si debe usar TextBlock entonces debe alinearlo con respecto a su padre.

Sin embargo, si puede usar Label en su lugar (y tienen una funcionalidad muy similar), entonces puede posicionar el contenido del texto:

<Label VerticalContentAlignment="Center" HorizontalContentAlignment="Center">
   I am centred text!
</Label>

El Label se estirará para llenar sus límites por defecto, lo que significa que el texto de la etiqueta estará centrado.

 0
Author: Drew Noakes,
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-12-12 21:03:36