WPF文本块中的文本垂直对齐

时间:2022-09-13 08:36:06

How do I assign vertical center alignment to the text inside a TextBlock? I found TextAlignment property but it is for horizontal text alignment. How do I do it for vertical text alignment?

如何为文本块中的文本分配垂直中心对齐?我找到了textalialigned属性,但它用于水平文本对齐。如何进行垂直文本对齐?

16 个解决方案

#1


230  

A Textblock itself can't do vertical alignment

Textblock本身不能进行垂直对齐

The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.

我发现最好的方法是将textblock放到边框中,这样边框就可以为你对齐。

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

Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable

注意:这在功能上等同于使用网格,这取决于您希望控件如何与布局的其他部分相匹配,以确定哪个控件更适合

#2


82  

While Orion Edwards Answer works for any situation, it may be a pain to add the border and set the properties of the border every time you want to do this. Another quick way is to set the padding of the text block:

虽然Orion Edwards的回答适用于任何情况,但每次你想要添加边框并设置边界属性时,这可能是一种痛苦。另一种快速的方法是设置文本块的填充:

<TextBlock Height="22" Padding="3" />

#3


47  

The TextBlock doesn't support vertical text alignment.

TextBlock不支持垂直文本对齐。

I work around this by wrapping the text block with a Grid and setting HorizontalAlignment="Stretch" and VerticalAlignment="Center".

我通过将文本块包装成一个网格并设置horizontal对齐="Stretch"和vertical对齐="Center"来解决这个问题。

Like this:

是这样的:

    <Grid>
        <TextBlock 
            HorizontalAlignment="Stretch"
            VerticalAlignment="Center"
            Text="Your text" />
    </Grid>

#4


15  

You can use label instead of textblock.

你可以用label代替textblock。

<Label Content="Hello, World!">
    <Label.LayoutTransform>
        <RotateTransform Angle="270"/>
    </Label.LayoutTransform>
</Label>

#5


2  

If you can do without the text wrapping, I think that replacing the TextBlock with a Label is the most succinct way to do this. Otherwise follow one of the other valid answers.

如果不需要文本包装,我认为用标签替换文本块是最简洁的方法。否则遵循其他有效答案之一。

<Label Content="Some Text" VerticalAlignment="Center"/>

#6


1  

For me, VerticalAlignment="Center" fixes this problem.
This could be because the TextBlockis wrapped in a grid, but then so is practically everything in wpf.

对我来说,垂直对齐=“Center”解决了这个问题。这可能是因为TextBlockis封装在一个网格中,但实际上wpf中的所有东西也是如此。

#7


1  

I've found that modifying the textbox style (ie: controltemplate) and then modifying the PART_ContentHost vertical alignment to Center will do the trick

我发现,修改文本框样式(即:controltemplate),然后修改PART_ContentHost垂直对齐到Center将发挥作用

#8


1  

Just for giggles, give this XAML a whirl. It isn't perfect as it is not an 'alignment' but it allows you to adjust text alignment within a paragraph.

只是为了好玩,试一试XAML。它不是完美的,因为它不是“对齐”,但是它允许你在一个段落中调整文本对齐。

<TextBlock>
    <TextBlock BaselineOffset="30">One</TextBlock>
    <TextBlock BaselineOffset="20">Two</TextBlock>  
    <Run>Three</Run>            
    <Run BaselineAlignment="Subscript">Four</Run>   
</TextBlock>

#9


1  

If you can overlook the height of TextBlock, it's better for you to use this:

如果你可以忽略TextBlock的高度,最好使用以下方法:

<TextBlock Height="{Binding}" Text="Your text"
TextWrapping="Wrap" VerticalAlignment="Center" Width="28"/>

#10


1  

In my case, I did this to make the TextBlock display nicer.

在我的例子中,我这样做是为了让TextBlock显示得更好。

<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>

The trick to make the text further from the bottom is to set

使文本离底更远的诀窍是设置

Margin="0,0,0,-5"

#11


1  

I found I had to do it slightly different. My problem was that if I changed the font size, the text would move up in the TextBox instead of stay on the bottom with the rest of TextBoxes on the line. By changing the vert alignment from top to bottom I was able to change the font programmatically from size 20 to size 14 & back, keeping text's gravity on the bottom and keeping things neat. Here's how:

我发现我必须做一些稍微不同的事情。我的问题是,如果我改变字体大小,文本就会在文本框中向上移动,而不是在文本框的其余部分保持在底部。通过从上到下更改vert对齐方式,我可以通过编程方式将字体从20号更改为14号和14号,将文本的重心保持在底部并保持整洁。方法如下:

WPF文本块中的文本垂直对齐

#12


1  

WPF文本块中的文本垂直对齐

To expand on the answer provided by @Orion Edwards, this is how you would do fully from code-behind (no styles set). Basically create a custom class that inherits from Border which has its Child set to a TextBox. The example below assumes that you only want a single line and that the border is a child of a Canvas. Also assumes you would need to adjust the MaxLength property of the TextBox based on the width of the Border. The example below also sets the cursor of the Border to mimic a Textbox by setting it to the type 'IBeam'. A margin of '3' is set so that the TextBox isn't absolutely aligned to the left of the border.

要扩展@Orion Edwards提供的答案,您可以通过代码隐藏(不设置样式)来完成。基本上创建一个自定义类,该类继承自边框,边框的子属性设置为文本框。下面的示例假设您只想要一条线,并且边框是画布的子元素。还假设您需要根据边框的宽度调整文本框的MaxLength属性。下面的示例还将边框的光标设置为“IBeam”,以模拟文本框。设置一个'3'的空白,这样文本框就不会完全对齐边框的左边。

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);

Class:

类:

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;
        }
    }
}

#13


0  

You can see my blog post. You can set custom height of Textblock from codebehind. For setting custom height you need to set it inside in a border or stackpanel

你可以看到我的博客。您可以从codebehind设置Textblock的自定义高度。要设置自定义高度,需要在边框或堆栈面板中设置它

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

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

#14


0  

I think is better to use a Label(or TextBlock) into a Label, you can't attach a mouse event directly in the border control, finally it is attached in the TextBlock, this is my recomendation:

我认为最好将标签(或文本块)添加到标签中,你不能直接在边框控件上附加鼠标事件,最后在TextBlock中附加,这是我的修改:

<Label 
    Height="32"
    VerticalContentAlignment="Center"
    HorizontalContentAlignment="Stretch"
    MouseLeftButtonUp="MenuItem_MouseLeftButtonUp">
    <TextBlock Padding="32 0 10 0">
        Label with click event
    </TextBlock>
</Label>

#15


0  

  <TextBox AcceptsReturn="True" 
           TextWrapping="Wrap"  
           VerticalContentAlignment="Top" >
  </TextBox>

#16


0  

TextBlock doesn't support vertical alignment of its content. If you must use TextBlock then you have to align it with respect to its parent.

TextBlock不支持内容的垂直对齐。如果必须使用TextBlock,那么就必须对它的父类进行对齐。

However if you can use Label instead (and they do have very similar functionality) then you can position the text content:

但是,如果您可以使用Label(它们确实有非常相似的功能),那么您可以放置文本内容:

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

The Label will stretch to fill its bounds by default, meaning the label's text will be centred.

默认情况下,标签将会被拉伸以填充它的边界,这意味着标签的文本将以中心为中心。

#1


230  

A Textblock itself can't do vertical alignment

Textblock本身不能进行垂直对齐

The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.

我发现最好的方法是将textblock放到边框中,这样边框就可以为你对齐。

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

Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable

注意:这在功能上等同于使用网格,这取决于您希望控件如何与布局的其他部分相匹配,以确定哪个控件更适合

#2


82  

While Orion Edwards Answer works for any situation, it may be a pain to add the border and set the properties of the border every time you want to do this. Another quick way is to set the padding of the text block:

虽然Orion Edwards的回答适用于任何情况,但每次你想要添加边框并设置边界属性时,这可能是一种痛苦。另一种快速的方法是设置文本块的填充:

<TextBlock Height="22" Padding="3" />

#3


47  

The TextBlock doesn't support vertical text alignment.

TextBlock不支持垂直文本对齐。

I work around this by wrapping the text block with a Grid and setting HorizontalAlignment="Stretch" and VerticalAlignment="Center".

我通过将文本块包装成一个网格并设置horizontal对齐="Stretch"和vertical对齐="Center"来解决这个问题。

Like this:

是这样的:

    <Grid>
        <TextBlock 
            HorizontalAlignment="Stretch"
            VerticalAlignment="Center"
            Text="Your text" />
    </Grid>

#4


15  

You can use label instead of textblock.

你可以用label代替textblock。

<Label Content="Hello, World!">
    <Label.LayoutTransform>
        <RotateTransform Angle="270"/>
    </Label.LayoutTransform>
</Label>

#5


2  

If you can do without the text wrapping, I think that replacing the TextBlock with a Label is the most succinct way to do this. Otherwise follow one of the other valid answers.

如果不需要文本包装,我认为用标签替换文本块是最简洁的方法。否则遵循其他有效答案之一。

<Label Content="Some Text" VerticalAlignment="Center"/>

#6


1  

For me, VerticalAlignment="Center" fixes this problem.
This could be because the TextBlockis wrapped in a grid, but then so is practically everything in wpf.

对我来说,垂直对齐=“Center”解决了这个问题。这可能是因为TextBlockis封装在一个网格中,但实际上wpf中的所有东西也是如此。

#7


1  

I've found that modifying the textbox style (ie: controltemplate) and then modifying the PART_ContentHost vertical alignment to Center will do the trick

我发现,修改文本框样式(即:controltemplate),然后修改PART_ContentHost垂直对齐到Center将发挥作用

#8


1  

Just for giggles, give this XAML a whirl. It isn't perfect as it is not an 'alignment' but it allows you to adjust text alignment within a paragraph.

只是为了好玩,试一试XAML。它不是完美的,因为它不是“对齐”,但是它允许你在一个段落中调整文本对齐。

<TextBlock>
    <TextBlock BaselineOffset="30">One</TextBlock>
    <TextBlock BaselineOffset="20">Two</TextBlock>  
    <Run>Three</Run>            
    <Run BaselineAlignment="Subscript">Four</Run>   
</TextBlock>

#9


1  

If you can overlook the height of TextBlock, it's better for you to use this:

如果你可以忽略TextBlock的高度,最好使用以下方法:

<TextBlock Height="{Binding}" Text="Your text"
TextWrapping="Wrap" VerticalAlignment="Center" Width="28"/>

#10


1  

In my case, I did this to make the TextBlock display nicer.

在我的例子中,我这样做是为了让TextBlock显示得更好。

<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>

The trick to make the text further from the bottom is to set

使文本离底更远的诀窍是设置

Margin="0,0,0,-5"

#11


1  

I found I had to do it slightly different. My problem was that if I changed the font size, the text would move up in the TextBox instead of stay on the bottom with the rest of TextBoxes on the line. By changing the vert alignment from top to bottom I was able to change the font programmatically from size 20 to size 14 & back, keeping text's gravity on the bottom and keeping things neat. Here's how:

我发现我必须做一些稍微不同的事情。我的问题是,如果我改变字体大小,文本就会在文本框中向上移动,而不是在文本框的其余部分保持在底部。通过从上到下更改vert对齐方式,我可以通过编程方式将字体从20号更改为14号和14号,将文本的重心保持在底部并保持整洁。方法如下:

WPF文本块中的文本垂直对齐

#12


1  

WPF文本块中的文本垂直对齐

To expand on the answer provided by @Orion Edwards, this is how you would do fully from code-behind (no styles set). Basically create a custom class that inherits from Border which has its Child set to a TextBox. The example below assumes that you only want a single line and that the border is a child of a Canvas. Also assumes you would need to adjust the MaxLength property of the TextBox based on the width of the Border. The example below also sets the cursor of the Border to mimic a Textbox by setting it to the type 'IBeam'. A margin of '3' is set so that the TextBox isn't absolutely aligned to the left of the border.

要扩展@Orion Edwards提供的答案,您可以通过代码隐藏(不设置样式)来完成。基本上创建一个自定义类,该类继承自边框,边框的子属性设置为文本框。下面的示例假设您只想要一条线,并且边框是画布的子元素。还假设您需要根据边框的宽度调整文本框的MaxLength属性。下面的示例还将边框的光标设置为“IBeam”,以模拟文本框。设置一个'3'的空白,这样文本框就不会完全对齐边框的左边。

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);

Class:

类:

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;
        }
    }
}

#13


0  

You can see my blog post. You can set custom height of Textblock from codebehind. For setting custom height you need to set it inside in a border or stackpanel

你可以看到我的博客。您可以从codebehind设置Textblock的自定义高度。要设置自定义高度,需要在边框或堆栈面板中设置它

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

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

#14


0  

I think is better to use a Label(or TextBlock) into a Label, you can't attach a mouse event directly in the border control, finally it is attached in the TextBlock, this is my recomendation:

我认为最好将标签(或文本块)添加到标签中,你不能直接在边框控件上附加鼠标事件,最后在TextBlock中附加,这是我的修改:

<Label 
    Height="32"
    VerticalContentAlignment="Center"
    HorizontalContentAlignment="Stretch"
    MouseLeftButtonUp="MenuItem_MouseLeftButtonUp">
    <TextBlock Padding="32 0 10 0">
        Label with click event
    </TextBlock>
</Label>

#15


0  

  <TextBox AcceptsReturn="True" 
           TextWrapping="Wrap"  
           VerticalContentAlignment="Top" >
  </TextBox>

#16


0  

TextBlock doesn't support vertical alignment of its content. If you must use TextBlock then you have to align it with respect to its parent.

TextBlock不支持内容的垂直对齐。如果必须使用TextBlock,那么就必须对它的父类进行对齐。

However if you can use Label instead (and they do have very similar functionality) then you can position the text content:

但是,如果您可以使用Label(它们确实有非常相似的功能),那么您可以放置文本内容:

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

The Label will stretch to fill its bounds by default, meaning the label's text will be centred.

默认情况下,标签将会被拉伸以填充它的边界,这意味着标签的文本将以中心为中心。