防止在WPF DataGrid中选择多行
本文关键字:选择 DataGrid WPF | 更新日期: 2023-09-27 18:25:37
我在WPF数据网格中有以下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的可用选项为
- 单个
- 扩展
和选择单元是
- 单元格
- FullRow
- 单元格或行标题