First CanUserDeleteRows set to False,
Second set KeyUp event
And custom modified as follows DataGrid.Columns
<DataGrid x:Name="DG" KeyUp="DG_KeyUp" ItemsSource="{Binding }" CanUserDeleteRows="False" AutoGenerateColumns="True"> <DataGrid.Columns> <DataGridCheckBoxColumn Header="SingleCheckBox"> <DataGridCheckBoxColumn.CellStyle> <Style TargetType="DataGridCell"> <Setter Property="ContentTemplate" > <Setter.Value> <DataTemplate> <CheckBox x:Name="CB" Click="CB_Click"/> </DataTemplate> </Setter.Value> </Setter> </Style> </DataGridCheckBoxColumn.CellStyle> </DataGridCheckBoxColumn> </DataGrid.Columns> </DataGrid>
In CS Page modified:
Defines a List <DataRow> dataRow set Row to store the DataTable
CheckBox modify the Click event
as follows
//数据源
public DataTable dataTable;
public List<DataRow> dataRow = new List<DataRow>(); private void CB_Click(object sender, RoutedEventArgs e) { if (DG.SelectedItem != null) { var row = DG.SelectedItem as DataRowView; dataRow.Add(row.Row); } }
Modify the DataGrid KeyUp events are as follows
private void DG_KeyUp(object sender, KeyEventArgs e) { if(e.Key==Key.Delete) { if (dataRow.Count> 0) { for (var item = 0; item < dataRow.Count; item++) { dataTable.Rows.Remove(dataRow[item]); } dataRow.Clear(); } } }
The final shots