MSDN Community

WinUI Samples

Sample 002: Advanced Grid Layout with Responsive Behavior

This sample demonstrates how to create a responsive grid layout using WinUI's XAML grid features. It showcases how to define columns that automatically adjust their size based on available space, and how to use `Auto` sizing for flexible content. The layout is designed to adapt gracefully to different screen sizes.

XAML Code:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="1*"/>
        <ColumnDefinition Width="2*"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="1*"/>
    </Grid.RowDefinitions>

    <TextBlock Grid.Row="0" Grid.Column="0" Text="Header" Style="{StaticResource TitleTextBlockStyle}" Margin="10"/>
    <Button Grid.Row="0" Grid.Column="1" Content="Action Button" HorizontalAlignment="Right" Margin="10"/>
    <StackPanel Grid.Row="1" Grid.Column="0" Orientation="Vertical" Margin="10">
        <TextBlock Text="Sidebar Content" FontWeight="Bold"/>
        <ListBox ItemsSource="{x:Bind NavigationItems}" SelectionChanged="Navigation_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate x:DataType="local:NavItem">
                    <TextBlock Text="{x:Bind Name}" Padding="5"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </StackPanel>
    <Border Grid.Row="1" Grid.Column="1" Background="LightGray" CornerRadius="5" Margin="10">
        <TextBlock x:Name="ContentTextBlock" Text="Main Content Area" Padding="15" VerticalAlignment="Center" HorizontalAlignment="Center"/>
    </Border>
    <TextBlock Grid.Row="1" Grid.Column="2" Text="Status" VerticalAlignment="Bottom" Margin="10"/>
</Grid>

Interactive Example:

Adjust Grid Behavior

Item 1

Column 1*

Item 2

Column 2*

Item 3

Column Auto

Item 4

Column 1*

Item 5

Column 2*

Item 6

Column Auto

In this example, the Grid.ColumnDefinitions are set with weights. The first column takes up 1 fraction of the available space, the second takes 2 fractions, and the third adjusts its width to fit its content. Resize your browser window or use the slider to see how the grid columns adapt.