I have a DataGrid that has RowDetailsVisibilityMode set to "VisibleWhenSelected" so that the RowDetailsTemplate displays when I select a particular row. What I want is to be able to toggle the RowDetails visibility when I click the row again. By default, the RowDetails will be visible so long as its selected, but I want to essentially "unselect" the selected row if I click it again.
After trying a lot of things, I've found a sort of wacky solution that at least makes it so that I can toggle the visibility when I click the row:
private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
if (DataGrid.SelectedIndex == prevSelectedIndex) { //check if I'm clicking on what's already selected
DataGrid.SelectedIndex = -1; //collapses everything
}
prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
}
The delay makes sure that the SelectedIndex property is already updated when I check for the selected index. I wish I didn't have to use it - I would be happy to find a better solution.
The problem now, however, is that whenever I click anything in the RowDetails of the selected row, this event fires and the row details disappear again. I want to be able to somehow check that I only expand/collapse the row when I click the row itself, not when I click whatever's in the RowDetailsTemplate. Is that possible? I don't want to use an extra Expander button for each row.