user3066571 user3066571 - 1 month ago 6
C# Question

Add row of text above a grid of items

I'm building a grid via WPF, and it works great. I need to add a row, or bar, or something to display above the grid, that will have several text items on it that will get populated by code. I've been tooling around, and I can't seem to figure out how to put another panel above my existing (and working) grid. This is my code:

<Window x:Class="GridWPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Board" SizeToContent="WidthAndHeight" Height="Auto" Width="Auto">
<Window.Resources>
<DataTemplate x:Key="DataTemplate_2">
<Button Content="{Binding}" Height="25" Width="25" Margin="0,0,0,0"/>
</DataTemplate>
<DataTemplate x:Key="DataTemplate_1">
<ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_2}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</DataTemplate>
</Window.Resources>
<Grid Name="GridBoard" ShowGridLines="True">
<ItemsControl x:Name="GridItems" ItemTemplate="{DynamicResource DataTemplate_1}"/>
</Grid>
</Window>


The GridItems gets populated by a jagged array, and displays fine. I just need to put a few text objects above it, be it boxes, or just a horizontal panel that fits the width of the grid.

Answer

May be the simplest option is to add a wrapper Grid and put your inner Grid in the second row. So, you will have the frist row (row 0) to put anything you need there.

<Window x:Class="GridWPF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Board" SizeToContent="WidthAndHeight" Height="Auto" Width="Auto">
<Window.Resources>
    <DataTemplate x:Key="DataTemplate_2">
        <Button Content="{Binding}" Height="25" Width="25" Margin="0,0,0,0"/>
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate_1">
        <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_2}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </DataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid>
        <!-- WHATEVER YOU NEED -->
    </Grid>

    <Grid Name="GridBoard" ShowGridLines="True" Grid.Row="1">
        <ItemsControl x:Name="GridItems" ItemTemplate="{DynamicResource DataTemplate_1}"/>
    </Grid>
</Grid>