WPF StackPanel内容垂直对齐

问题描述 投票:7回答:3

有没有办法在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>
wpf xaml alignment stackpanel
3个回答
1
投票

您可以使用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>

0
投票

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

<Grid>
    <StackPanel VerticalAlignment="Center">
        ...
    </StackPanel
</Grid>

-3
投票

只要用这个:

<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
     <TextBlock/>
     <Button/>
     <TextBox/>
     <Button/>
     <TextBlock/>
</StackPanel>
© www.soinside.com 2019 - 2024. All rights reserved.