Search code examples
wpfxamldatagridrowdetailstemplate

WPF: DataGrid.RowDetailsTemplate: Only show details if single row is selected?


I'm using the RowDetailsTemplate in one of my DataGrids. This works fine so far, but looks really odd when the user wants to select multiple rows for specific operations. Is there a simple way to display the RowDetailsTemplate only if exactly only one row is selected?

I'd love to solve this with pure XAML. Otherwise I'd do it with code behind:

private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    DataGrid temp = sender as DataGrid;

    if (temp.SelectedItems.Count == 1)
    {
        temp.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
    }
    else
    {
        temp.RowDetailsVisibilityMode = DataGridRowDetailsVisibilityMode.Collapsed;
    }
}

Solution

  • DataGrid has a property RowDetailsVisibilityMode. Set it to Collapsed when more than one row is selected. Your XAML should look something like

    <DataGrid Name="dataGrid1" RowDetailsVisibilityMode="{Binding Path=SelectedItems.Count, RelativeSource={RelativeSource Self}, Converter={StaticResource rdtvc}}">
    

    and the corresponding converter like

    public class Converter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
    
            if (value != null && (int)value == 1)
                return DataGridRowDetailsVisibilityMode.VisibleWhenSelected;
            else 
                return DataGridRowDetailsVisibilityMode.Collapsed;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }