Search code examples
c#wpflistviewdatagrid

WPF multiple DataGrids in a ListView


Is it possible to put multiple DataGrids inside a ListView? Something like

<ListView ItemsSource="{Binding Schools}">
    <DataGrid ItemsSource="{Binding Schools.Teachers}" />
</ListView>

Where the classes are:

public class MainViewModel
{
    public ObservableCollection<School> Schools { get; set; }
}

public class School
{
    public ObservableCollection<Teacher> Teachers { get; set; }
}

public class Teacher
{
    public string Name { get; set; }
    public string ID { get; set; }
    public string Address { get; set; }
    public string Ranking { get; set; }
}

And the output would be basically a list of DataGrids, one DataGrid for each School.

School1
+-----------------+---------------+---------------+---------------+
| Name            | ID            | Address       | Ranking       |
+-----------------+---------------+---------------+---------------+
| Teacher1 Name   | Teacher1 ID   | Teacher1 Addr | Teacher1 Rank |
+-----------------+---------------+---------------+---------------+
| Teacher2 Name   | Teacher2 ID   | Teacher2 Addr | Teacher2 Rank |
+-----------------+---------------+---------------+---------------+

School2
+-----------------+---------------+---------------+---------------+
| Name            | ID            | Address       | Ranking       |
+-----------------+---------------+---------------+---------------+
| Teacher1 Name   | Teacher1 ID   | Teacher1 Addr | Teacher1 Rank |
+-----------------+---------------+---------------+---------------+
| Teacher2 Name   | Teacher2 ID   | Teacher2 Addr | Teacher2 Rank |
+-----------------+---------------+---------------+---------------+

How would I structure the xaml for this kind of display?


Solution

  • The DataGrid would be declared in a DataTemplate that is assigned to the ItemTemplate property of the ListBox (unless you set the View property of a ListView, use the simpler base class ListBox).

    Inside the DataTemplate the Binding would be ItemsSource="{Binding Teachers}".

    For details, see Data Templating Overview.

    <ListBox ItemsSource="{Binding Schools}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <DataGrid ItemsSource="{Binding Teachers}" />
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>