Search code examples
c#wpfdatagridexpression-blend

Multi-row datagrid to handle collection in a collection?


I have the following data structures

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

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

And I have people stored in an observable collection -

ObservableCollection<Person> People;

I need to display them in a DataGrid like this mockup - enter image description here

As you can see, a Person can have either one or more Cars, and when they have multiple cars I want to show the details of the multiple cars in the same 'row'.

Is this possible with WPF? How would I set up bindings if so?


Solution

  • does the RowDetailTemplate do what you want? you can use it to display childrows the way you want. just google for it to see some more examples

    <DataGrid ItemsSource="{Binding People}">
      <DataGrid.Columns>
         <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
         <DataGridTextColumn Header="First Name" Binding="{Binding FirstName}"/>
         <DataGridTextColumn Header="Last Name" Binding="{Binding Surname}"/>
       </DataGrid.Columns>
       <DataGrid.RowDetailsTemplate>
          <DataTemplate>
              <DataGrid ItemsSource="{Binding Cars}">
               <DataGridTextColumn Binding="{Binding Path=CarModel}" Header="Model" />
               <DataGridTextColumn Binding="{Binding Path=CarAge}" Header="Age" />
              <DataGridTextColumn Binding="{Binding Path=CarColor}" Header="Color" />
             </DataGrid>
            </DataTemplate>
         </DataGrid.RowDetailsTemplate>
        </DataGrid>