简体   繁体   English

阻止WPF DataGrid中的多行选择

[英]Prevent multiple row selection in WPF DataGrid

I have the following XAML markup in a WPF 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>

Is it possible to prevent users from selecting multiple rows while holding down the Ctrl key or selecting multiple rows with a mouse? 是否可以阻止用户在按住Ctrl键或用鼠标选择多行的同时选择多行?

I've tried the following code in the SelectionChanged event but it does not work: 我在SelectionChanged事件中尝试了以下代码,但它不起作用:

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

Try specifying <DataGrid SelectionMode="Single" and optionally SelectionUnit="FullRow" 尝试指定<DataGrid SelectionMode="Single"并选择SelectionUnit="FullRow"

The available options for SelectionMode are SelectionMode的可用选项是

  • Single
  • Extended 扩展

and for SelectionUnit are 而对于SelectionUnit则是

  • Cell 细胞
  • FullRow FullRow
  • CellOrRowHeader CellOrRowHeader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM