如何在StackPanel内垂直对齐TextBox?

Edw*_*uay 12 xaml stackpanel

在下面的XAML中,单词"Test" 水平居中但不垂直居中.

如何让它垂直居中?

<Window x:Class="TestVerticalAlign2343.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        WindowStartupLocation="CenterScreen"
    Title="Window1" Height="768" Width="1024">
    <DockPanel LastChildFill="True">
        <Slider x:Name="TheSlider"
                DockPanel.Dock="Left"
                Orientation="Vertical"
                HorizontalAlignment="Center"
                HorizontalContentAlignment="Center"
                Minimum="0"
                Maximum="10"
                Cursor="Hand"
                Value="{Binding CurrentSliderValue}"
                IsDirectionReversed="True"
                IsSnapToTickEnabled="True"
                Margin="10 10 0 10"/>
        <Border DockPanel.Dock="Right" Background="Beige"
                Padding="10"
                Margin="10"
                CornerRadius="5">
            <StackPanel Height="700">
                <TextBlock
                    Text="Test"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    FontSize="200" x:Name="TheNumber"/>

            </StackPanel>
        </Border>
    </DockPanel>
</Window>
Run Code Online (Sandbox Code Playgroud)

san*_*osc 17

无论你如何拉伸它,堆叠板都会在孩子周围坍塌.你不能让它成长得更多.基本上,"高度= 700"并没有帮助你.

因此,要么将StackPanel上的VerticalAlignment设置为"center",以便stackpanel进入dockpanel的中心...或者完全删除stackpanel并在TextBlock上设置VerticalAlignment ="Center".

  • +1"对于一个堆叠板,无论你如何拉伸它,都会在它的孩子周围坍塌". (5认同)

Edw*_*uay 11

看来我10个月之前问这个问题,我得到了上面的场景通过更换工作的StackPanelDockPanel中LastChildFill =真这样的:

<DockPanel LastChildFill="True">
    <TextBlock
        DockPanel.Dock="Top"
        Text="Test"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        FontSize="200" x:Name="TheNumber"/>
</DockPanel>
Run Code Online (Sandbox Code Playgroud)


Del*_*ics 5

我偶然发现了这似乎完美无缺:

<Grid>
    <TextBlock Text="My Centered Text"
               TextAlignment="Center" 
               VerticalAlignment="Center"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

Grid确保其中的单个TextBox填充网格中的单个单元格,TextBlock中的VerticalAlignment确保文本居中于其中.

只需根据需要水平放置/对齐文本(上面的片段也将其置于此轴中,但更改此值不会改变垂直居中).