我在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;
    }
}

最佳答案

尝试指定<DataGrid SelectionMode="Single"以及可选的SelectionUnit="FullRow"
SelectionMode的可用选项是

  • 单个
  • 扩展的

  • 和SelectionUnit是
  • 细胞
  • FullRow
  • CellOrRowHeader
  • 09-25 21:57