I have a multi-layer nested DataGrid.
This is when nothing is selected:
This is when I click the first row. It expands the row detail:
This is when I click the first row in the row detail:
Then I click the second row of the outer DataGrid:
If I click the first row now, row detail of both levels are displayed (because it was previously selected):
Is there a way to make sure when I click a new row, all the row detail of the previous selected row will be collapsed? In this example it is a 3 layer nested DataGrid. It could have more layers.
My code looks something like this:
<DataGrid x:Name="dataGrid1" ItemsSource="{Binding Students}" AutoGenerateColumns="False" IsReadOnly="True" HeadersVisibility="Column" Background="DarkBlue">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
<DataGridTextColumn Header="School" Binding="{Binding School}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<DataGrid x:Name="nestedDataGrid1" ItemsSource="{Binding Teachers}" IsReadOnly="True" AutoGenerateColumns="False" HeadersVisibility="Column" Background="DarkRed">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<TextBlock Text="Line 1" FontSize="30"/>
<TextBlock Text="Line 2" FontSize="30"/>
<TextBlock Text="Line 3" FontSize="30"/>
<TextBlock Text="Line 4" FontSize="30"/>
<TextBlock Text="Line 5" FontSize="30"/>
</StackPanel>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
One solution I came up with is to set
SelectedIndex = -1for the inner DataGrid when a new row is selected on the outer DataGrid. WhatSelectedIndex = -1does is basically unselecting which will do that job. If you have a 5-layer nestedDataGrid, you will need 5 integers to track all theSelectedIndexfor each layer.It is like this:
In this case, you just need to set
SelectedIndex = -1in your view model whenever you want to unselect a data grid row.