Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent multiple row selection in WPF DataGrid

I have the following XAML markup in a WPF DataGrid:

<DataGrid ItemsSource="{Binding ResultList}" Grid.ColumnSpan="4" Grid.Row="7" Height="150" 
          HorizontalAlignment="Left" Margin="10,0,0,0" Name="gvResults" 
          VerticalAlignment="Bottom" Width="590" AutoGenerateColumns="False" SelectionChanged="gvResults_SelectionChanged"
           SelectionUnit="FullRow">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True" Binding="{Binding Name}" Header="Name" ScrollViewer.VerticalScrollBarVisibility="Auto" Width="190" />
        <DataGridTextColumn IsReadOnly="True" Binding="{Binding Surname}" Header="Surname" Width="190" />
        <DataGridTextColumn IsReadOnly="True" Binding="{Binding Age}" Header="Age" Width="*" />
    </DataGrid.Columns>
</DataGrid>

Is it possible to prevent users from selecting multiple rows while holding down the Ctrl key or selecting multiple rows with a mouse?

I've tried the following code in the SelectionChanged event but it does not work:

private void gvResults_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (gvResults.SelectedItems.Count > 1)
    {
        e.Handled = true;
    }
}
like image 980
Denys Wessels Avatar asked Feb 22 '12 13:02

Denys Wessels


1 Answers

Try specifying <DataGrid SelectionMode="Single" and optionally SelectionUnit="FullRow"

The available options for SelectionMode are

  • Single
  • Extended

and for SelectionUnit are

  • Cell
  • FullRow
  • CellOrRowHeader
like image 121
Phil Avatar answered Oct 07 '22 12:10

Phil