WPF StackPanel内容垂直对齐

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF StackPanel内容垂直对齐相关的知识,希望对你有一定的参考价值。

有没有办法在XAML说我想要垂直居中对齐水平导向的StackPanel内的所有组件?

我用下面的XAML达到了预期的效果:

<StackPanel Orientation="Horizontal">
     <TextBlock VerticalAlignment="Center"/>
     <Button VerticalAlignment="Center"/>
     <TextBox VerticalAlignment="Center"/>
     <Button VerticalAlignment="Center"/>
     <TextBlock VerticalAlignment="Center"/>
</StackPanel>

但我需要分别为每个控件重复VerticalAlignment="Center"

有没有办法在StackPanel级别声明类似下面的内容?

<StackPanel Orientation="Horizontal" VERTICALCONTENTALIGNMENT="Center">
     <TextBlock/>
     <Button/>
     <TextBox/>
     <Button/>
     <TextBlock/>
</StackPanel>
答案

您可以使用StackPanelTrigger定义样式,该样式设置所有孩子的VerticalAlignment

<Style x:Key="HorizontalStackPanel" TargetType="{x:Type StackPanel}">
    <Setter Property="Orientation" Value="Horizontal" />
    <Style.Triggers>
        <Trigger Property="Orientation" Value="Horizontal">
            <Setter Property="FrameworkElement.VerticalAlignment"  Value="Center" />
        </Trigger>
    </Style.Triggers>
</Style>

并应用此样式:

<StackPanel Style="{StaticResource HorizontalStackPanel}">
    <TextBlock />
    <Button />
    <TextBox />
    <Button />
    <TextBlock />
</StackPanel>

这个对我有用。整个代码:

<Window x:Class="WpfApplication11.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="HorizontalStackPanel" TargetType="{x:Type StackPanel}">
            <Setter Property="Orientation" Value="Horizontal" />
            <Style.Triggers>
                <Trigger Property="Orientation" Value="Horizontal">
                    <Setter Property="FrameworkElement.VerticalAlignment"  Value="Center" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <StackPanel Style="{StaticResource HorizontalStackPanel}">
            <TextBlock Text="One"/>
            <Button Content="Two"/>
            <TextBox Text="Three"/>
            <Button Content="Four"/>
            <TextBlock Text="Five"/>
        </StackPanel>
    </Grid>
</Window>
另一答案

StackPanel放入Grid并在VerticalAlignment="Center"上设置StackPanel

<Grid>
    <StackPanel VerticalAlignment="Center">
        ...
    </StackPanel
</Grid>
另一答案

只要用这个:

<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
     <TextBlock/>
     <Button/>
     <TextBox/>
     <Button/>
     <TextBlock/>
</StackPanel>

以上是关于WPF StackPanel内容垂直对齐的主要内容,如果未能解决你的问题,请参考以下文章

wpf界面StackPanel怎么往左对齐?

WPF Grid与Stackpanel

WPF StackPanel 垂直框架全高

WPF 按钮中的文本内容未垂直居中

对齐按钮内容

2021-08-16 WPF控件专题 StackPanel 控件详解