首先将CanUserDeleteRows设置为False,

其次是设置KeyUp事件

并自定义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>

 

在CS页面修改:

定义一个List<DataRow> dataRow 集合用来存储DataTable的Row

修改CheckBox的Click事件

如下

        //数据源
 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); } }

修改DataGrid的KeyUp事件如下

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();
                     
                } 
            }
        }

 

最终截图

WPF DataGrid使用DataTable为数据源,添加CheckBox列使用Delete删除行的方法

相关文章:

  • 2022-02-13
  • 2022-12-23
  • 2021-10-20
  • 2021-07-15
  • 2022-03-04
  • 2022-03-05
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-08-31
相关资源
相似解决方案