Tuesday, July 3, 2012

WPF DataGrid RowDetailsTemplate

WPF DataGrid provides a Row Details feature. Row details is simply a panel that shown for a selected row. Row Details may contain any thing you want to put there - label, textbox, button, picture...
WPF DataGrid RowDetailsTemplate example

In my example Row Details contains only two labels, let's take a look on MainWindow.xaml:
<Grid>
    <DataGrid ItemsSource="{Binding Employees}" AutoGenerateColumns="False">
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <DockPanel>                            
                    <Label Content="Age: "/>
                    <Label Content="{Binding Age}"/>
                </DockPanel>
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
        
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" 
                                IsReadOnly="True"
                                Binding="{Binding Name}"/>
            <DataGridTextColumn Header="Email" 
                                IsReadOnly="True"
                                Binding="{Binding Email}"/>
            <DataGridTextColumn Header="Position" 
                                IsReadOnly="True"
                                Binding="{Binding Position}"/>
        </DataGrid.Columns>
    </DataGrid>
</Grid>
Inside DataTemplate you can put anything you want, as you can see for this particular example I put two labels into DockPanel. Once user clicks on specific row Row Details will be shown automatically.
This is what we like in WPF - the flexibility it gives for a developer. Every control is a container - an infinite number of variation for creating GUI application.

Download the source code of this example (Visual Studio 2010).

4 comments:

  1. I've had good success putting another datagrid inside there, so you can drop down and display a whole set of related details easily - it gets a bit tricky with column headers, but for the right application, can work really well.

    ReplyDelete
  2. how did you put another datagrid inside?

    ReplyDelete
    Replies
    1. Just put another DataGrid inside DataTemplate element.

      Delete