XAML Layout Fundamentals
Understanding how to arrange UI elements in XAML is essential for building fluid, responsive Windows applications. This guide covers the primary layout panels, their properties, and best practices.
Common Layout Panels
- Grid – Two‑dimensional layout with rows and columns.
- StackPanel – Stacks children vertically or horizontally.
- Canvas – Absolute positioning using coordinates.
- DockPanel – Dock children to top, bottom, left, right, or fill.
- WrapPanel – Wraps content to the next line when space runs out.
Grid Example
<Grid Margin="20">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.ColumnSpan="2"
Text="Header" FontSize="24"
HorizontalAlignment="Center"/>
<ListBox Grid.Row="1" Grid.Column="0"
ItemsSource="{Binding Items}"
Margin="5"/>
<StackPanel Grid.Row="1" Grid.Column="1"
Margin="5">
<Button Content="Add" Width="80"/>
<Button Content="Remove" Width="80" Margin="0,5,0,0"/>
</StackPanel>
</Grid>
Responsive Design with Viewbox
The Viewbox
scales its child element, making UI adaptable to different screen sizes.
<Viewbox Stretch="Uniform">
<Grid Width="400" Height="300">
... layout ...
</Grid>
</Viewbox>
Comments
Leave a Comment