我如何分配垂直中心对齐到文本块内的文本?我发现TextAlignment属性,但它是水平文本对齐。我怎么做垂直文本对齐?


当前回答

在我的情况下,我这样做是为了使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>

使文本离底部更远的技巧是设置

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

其他回答

如果你可以忽略TextBlock的高度,你最好使用这个:

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

你可以使用标签而不是文本块。

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

我发现我必须做一些不同的事情。我的问题是,如果我改变字体大小,文本将在文本框中向上移动,而不是保持在底部与其余的文本框在一行。通过改变从上到下的垂直对齐,我能够以编程方式将字体大小从20改为14并返回,保持文本的重心在底部,并保持整洁。方法如下:

实现您在这里谈论的内容的最佳方法是创建一个支持VerticalContentAlignment的标签

然后,如果你真的需要一些标签不涵盖的TextBlock属性,如TextWrapping,你可以在你的标签内放置一个TextBlock

结果满足了你的需求,VerticalContentAlignment和textwrap

<Label
   VerticalContentAlignment="Center">
   <TextBlock
             TextWrapping="WrapWithOverflow">
             My text goes here!
   </TextBlock> 
<Label/>

TextBlock不支持垂直文本对齐。

我通过用网格包装文本块并设置horizontalalign ="Stretch"和verticalalign ="Center"来解决这个问题。

是这样的:

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