简体   繁体   English

WPF TextBlock 中的文本垂直对齐

[英]Text vertical alignment in WPF TextBlock

How do I assign vertical center alignment to the text inside a TextBlock?如何为 TextBlock 内的文本指定垂直居中对齐方式? I found TextAlignment property but it is for horizontal text alignment.我找到了 TextAlignment 属性,但它用于水平文本对齐。 How do I do it for vertical text alignment?如何进行垂直文本对齐?

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.我发现做到这一点的最佳方法是将文本块放在边框内,以便边框为您进行对齐。

<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注意:这在功能上等同于使用网格,它只取决于您希望控件如何适应布局的其余部分,哪个更合适

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.虽然Orion Edwards Answer适用于任何情况,但每次要添加边框并设置边框的属性时可能会很痛苦。 Another quick way is to set the padding of the text block:另一种快速的方法是设置文本块的填充:

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

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".我通过用网格包裹文本块并设置 Horizo​​ntalAlignment="Stretch" 和 VerticalAlignment="Center" 来解决这个问题。

Like this:像这样:

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

You can use label instead of textblock.您可以使用标签而不是文本块。

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

TextBlock doesn't support vertical alignment of its content. TextBlock不支持其内容的垂直对齐。 If you must use TextBlock then you have to align it with respect to its parent.如果您必须使用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.默认情况下, Label将拉伸以填充其边界,这意味着标签的文本将居中。

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.如果你可以不用text wrapping ,我认为用 Label 替换 TextBlock 是最简洁的方法。 Otherwise follow one of the other valid answers.否则,请遵循其他有效答案之一。

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

For me, VerticalAlignment="Center" fixes this problem.对我来说, VerticalAlignment="Center"解决了这个问题。
This could be because the TextBlock is wrapped in a grid, but then so is practically everything in wpf.这可能是因为TextBlock被包裹在一个网格中,但实际上 wpf 中的所有内容也是如此。

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"

Just for giggles, give this XAML a whirl.只是为了咯咯笑,试一试这个 XAML。 It isn't perfect as it is not an 'alignment' but it allows you to adjust text alignment within a paragraph.它并不完美,因为它不是“对齐”,但它允许您调整段落内的文本对齐方式。

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

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

我发现,修改文本样式(即: controltemplate ),然后修改PART_ContentHost垂直对齐中心将做的伎俩

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.我的问题是,如果我更改字体大小,文本将在 TextBox 中向上移动,而不是留在底部,其余 TextBoxes 在线。 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.通过从上到下更改垂直对齐,我能够以编程方式将字体从 20 号更改为 14 号并返回,从而将文本的重力保持在底部并保持整洁。 Here's how:就是这样:

在此处输入图片说明

垂直对齐的单行文本框。

To expand on the answer provided by @Orion Edwards, this is how you would do fully from code-behind (no styles set).为了扩展@Orion Edwards 提供的答案,这就是您完全从代码隐藏(未设置样式)的方式。 Basically create a custom class that inherits from Border which has its Child set to a TextBox.基本上创建一个继承自 Border 的自定义类,该类将其 Child 设置为 TextBox。 The example below assumes that you only want a single line and that the border is a child of a Canvas.下面的示例假设您只需要一行并且边框是 Canvas 的子元素。 Also assumes you would need to adjust the MaxLength property of the TextBox based on the width of the Border.还假设您需要根据边框的宽度调整 TextBox 的 MaxLength 属性。 The example below also sets the cursor of the Border to mimic a Textbox by setting it to the type 'IBeam'.下面的示例还通过将边框的光标设置为类型“IBeam”来模拟文本框。 A margin of '3' is set so that the TextBox isn't absolutely aligned to the left of the border.设置了 '3' 的边距,以便 TextBox 不会绝对与边框的左侧对齐。

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

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:我觉得用Label(或者TextBlock)变成Label比较好,不能直接在边框控件中附加鼠标事件,最后附加在TextBlock中,这是我的推荐:

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

I think it's wise to use a textbox with no border and background as an easy and fast way to reach center aligned textblock我认为使用没有边框和背景的文本框作为到达居中对齐文本块的简单快捷的方法是明智的

<TextBox
TextWrapping="Wrap"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
Background="{x:Null}"
BorderBrush="{x:Null}"
/>

You can see my blog post.你可以看看我的博文。 You can set custom height of Textblock from codebehind.您可以从代码隐藏设置 Textblock 的自定义高度。 For setting custom height you need to set it inside in a border or stackpanel要设置自定义高度,您需要将其设置在边框或堆栈面板中

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM