Friday, 7 August 2015

Horizontal Alignment And Vertical alignment in WPF





HorizontalAlignment. WPF controls can be aligned. With the HorizontalAlignment and VerticalAlignment attributes, we anchor controls to edges or center them. We can also stretch controls to fill the available space.

Example. This example shows both HorizontalAlignment and VerticalAlignment. I added five Buttons to a Grid in a Window. I left the default Width of each Button, but changed the alignment properties.

Example
Window x:Class="WpfTutorialSamples.Panels.StackPanel"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="StackPanel" Height="160" Width="300">
        <StackPanel Orientation="Horizontal">
                <Button VerticalAlignment="Top">Button 1</Button>
                <Button VerticalAlignment="Center">Button 2</Button>
                <Button VerticalAlignment="Bottom">Button 3</Button>
                <Button VerticalAlignment="Bottom">Button 4</Button>
                <Button VerticalAlignment="Center">Button 5</Button>
                <Button VerticalAlignment="Top">Button 6</Button>
        </StackPanel>
</Window>
A StackPanel in Vertical mode with differently aligned controls

Button
Left, Top:
This is the first Button. It is on the left side of the window at the top.
Left, Bottom:
This Button has a HorizontalAlignment of Left, and a vertical one of "Bottom," so it is at the bottom left.
Left, Center:
The third button is located on the left edge, vertically centered. Its position changes as the window resizes.
Center, Center:
This Button will always be located in the center of the window. Try resizing the window: it remained centered.
Right, Stretch:

This Button uses Stretch for its VerticalAlignment. This means it expands to fill the vertical space.




Below Chart will help you to identify which alignment you have to give. Hope this useful.






2 comments: