I have a DataGrid who’s RowDetails is set to show when selected (RowDetailsVisibilityMode=”VisibleWhenSelected”). Now I want to be able to get rid of it! I put a close button on the row details with this code:
private void Button_Click(object sender, RoutedEventArgs e)
{
e.Handled = true;
Button button = sender as Button;
DataGridRow row = button.FindAncestor<DataGridRow>();
row.DetailsVisibility = Visibility.Collapsed;
}
That code gets me 90% there, but once the row details is collapsed for a given row it will not appear the next time that row is selected.
I’ve run into this too. Here’s a solution:
Keep that button in the RowDetails and change its code a little. Rather than focusing on the individual row’s visibility, set the DataGrid’s SelectedIndex property to -1 (none selected).
Since your RowDetailsVisibilityMode is
VisibleWhenSelected, the DataGrid will collapse/hide any expanded RowDetails. This works well when the SelectionMode isSingle.