阻止WPF DataGrid中的多行选择

时间:2012-02-22 13:43:14

标签: c# wpf xaml datagrid

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

1 个答案:

答案 0 :(得分:52)

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

SelectionMode的可用选项是

  • 扩展

和SelectionUnit是

  • 细胞
  • FullRow
  • CellOrRowHeader