Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF StackPanel content vertical alignment

Is there a way in XAML to say that I want to center-align vertically all components inside a horizontal-oriented StackPanel?

I achieve the desired result with the below XAML:

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

But I need to repeat the VerticalAlignment="Center" for each control separately.

Is there a way to declare on the StackPanel level something like below?

<StackPanel Orientation="Horizontal" VERTICALCONTENTALIGNMENT="Center">
     <TextBlock/>
     <Button/>
     <TextBox/>
     <Button/>
     <TextBlock/>
</StackPanel>
like image 711
Nuts Avatar asked Apr 15 '15 08:04

Nuts


2 Answers

Put the StackPanel inside a Grid and set VerticalAlignment="Center" on the StackPanel

<Grid>
    <StackPanel VerticalAlignment="Center">
        ...
    </StackPanel
</Grid>
like image 158
Mauro Sampietro Avatar answered Sep 30 '22 12:09

Mauro Sampietro


Define a style like this;

<Style x:Key="StackHorizontal" TargetType="StackPanel">
    <Style.Resources>
        <Style TargetType="TextBlock" BasedOn="{StaticResource {x:Type TextBlock}}">
            <Setter Property="VerticalAlignment"  Value="Center" />
        </Style>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="VerticalAlignment"  Value="Center" />
        </Style>
    </Style.Resources>
</Style>
like image 21
kaya Avatar answered Sep 30 '22 12:09

kaya