Aligning Items within LayoutGroup and LayoutControl Objects
- 3 minutes to read
For a child control within a LayoutGroup or LayoutControl, you can specify the alignment within its parent: anchor the control to a parent’s edge, center or stretch the control. To set the alignment, the HorizontalAlignment and VerticalAlignment properties of child controls are used.
The following XAML creates a LayoutGroup with three LayoutItems:
<lc:LayoutControl >
<lc:LayoutGroup Header="LayoutGroup" View="GroupBox">
<lc:LayoutItem Label="Item 1:">
<TextBox />
</lc:LayoutItem>
<lc:LayoutItem Label="Item 2:">
<TextBox/>
</lc:LayoutItem>
<lc:LayoutItem Label="Item 3:">
<TextBox />
</lc:LayoutItem>
</lc:LayoutGroup>
</lc:LayoutControl>
By default, LayoutItems are aligned to the top and stretched horizontally within a parent control. So, the code above produces the following result:
Whenever the group’s width is modified, the width of the LayoutItems is changed accordingly:
The following sections illustrate the HorizontalAlignment property in action. The VerticalAlignment property works identically.
Align items
The image below shows the same LayoutGroup. For the first LayoutItem, the HorizontalAlignment property is set to Left. For the second and third LayoutItems, the HorizontalAlignment property is set to Right:
When items are anchored to their parent’s edge, they shrink to their minimum size. If required, you can make the LayoutItems wider, changing their Width property, or changing the Width properties of their controls.
Center items
In the next image, for the second LayoutItem, the HorizontalAlignment property is set to Center. For the first and third LayoutItems, this property is set to Left and Right, respectively:
Stretch items
When an individual item is stretched, it occupies all the available empty space. If there are multiple items being stretched, the empty space is divided between them proportionally.
In the next image, the HorizontalAlignment property is set to Left, Stretch and Right for the three LayoutItems, respectively:
You’ll get the same layout of items if the third item’s alignment is set to Left. This item will be displayed after Item 2, since the items with the Stretch and Left alignment have the same visual order priority (items with the vertical alignment set to Top and Stretch also have the same visual order priority).
Visual order
When modifying the alignment of items, the visual order of the items may change. For instance, if you set an item’s HorizontalAlignment to Right, this item will be displayed after the items that have this property set to Left, Center or Stretch, even if this item is defined before them in XAML. The following image illustrates this feature, where the HorizontalAlignment property is set to Right, Stretch and Right for the three LayoutItems, respectively. Although Item 1 is defined first in XAML, it’s displayed after Item 2: