Search code examples
c#wpfdatagridexpression-blendwpfdatagrid

Row details in DataGrid - can I bind them to an 'inner' collection?


I have two data structures that look like this -

class Car
{
    string CarModel;
    string CarColor;
    string CarAge;
}

class Person
{
    int ID;
    string FirstName;
    string Surname;
    ObservableCollection<Car> Cars;
}

public ObservableCollection<Person> People { get; set; }

So I have a collection of type Car within a collection of type Person. I want to display this in a DataGrid that looks like this where each Person can have zero or more cars -

enter image description here

The following xaml code takes care of the rows but it doesn't handle the row details -

<DataGrid ItemsSource="{Binding People}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
            <DataGridTextColumn Header="Firstname" Binding="{Binding Firstname}"/>
            <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
        </DataGrid.Columns>
    </DataGrid>

Anyone know if it is possible to display a DataGrid with row details bound to an inner collection, (in this case ObservableCollection<Car> Cars)?


Solution

  • Just put something like an ItemsControl in the RowDetailsTemplate

    <DataGrid ItemsSource="{Binding People}" AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
            <DataGridTextColumn Header="Firstname" Binding="{Binding Firstname}"/>
            <DataGridTextColumn Header="Surname" Binding="{Binding Surname}"/>
        </DataGrid.Columns>
    
        <DataGrid.RowDetailsTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Cars}" ItemTemplate="{StaticResource CarTemplate}" />
            </DataTemplate>
        </DataGrid.RowDetailsTemplate>
    </DataGrid>