WPF StackPanel content vertical alignment

Nuts picture Nuts · Apr 15, 2015 · Viewed 15.8k times · Source

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>

Answer

Mauro Sampietro picture Mauro Sampietro · Sep 19, 2018

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

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