2012-02-22 165 views
15

我有一个WPF的DataGrid以下XAML标记:防止多行选择

<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> 

是否有可能阻止用户选择多行同时按住按Ctrl键或选择多行用鼠标?

我试过在SelectionChanged事件下面的代码,但它不工作:

private void gvResults_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (gvResults.SelectedItems.Count > 1) 
    { 
     e.Handled = true; 
    } 
} 

回答

47

尝试指定<DataGrid SelectionMode="Single" 和可选SelectionUnit="FullRow"

为的SelectionMode可用的选项

  • Single
  • Extended

和SelectionUnit是

  • 细胞
  • FullRow
  • CellOrRowHeader