3

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;
    }
}
Ralf
  • 293
  • 5
  • 15

2 Answers2

2

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();
    }
}
enapi
  • 708
  • 6
  • 18
  • ...and what would be the best way to do that? I'd love to do that in XAML, but I cannot think of a proper way to do that... – Ralf May 26 '14 at 12:25
2

Based on the answer by user1994514 I developed a XAML-only version without the need for a converter. In case someone wants to avoid the additional converter you can use a style with a data trigger to achieve the same effect.

    <DataGrid>
        <DataGrid.Style>
            <Style TargetType="DataGrid">
                <Setter Property="RowDetailsVisibilityMode" Value="Collapsed" />
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SelectedItems.Count, RelativeSource={RelativeSource Self}}" Value="1">
                        <Setter Property="RowDetailsVisibilityMode" Value="VisibleWhenSelected" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </DataGrid.Style>
    </DataGrid>