使用复选框和删除按钮从WPF Datagrid删除多行

时间:2017-07-12 01:52:37

标签: c# wpf checkbox datagrid

我有一个包含复选框的DataGrid。我想删除DataGrid中通过单击删除按钮检查复选框的所有行。我的数据网格的XAML如下所示。

    <DataGrid x:Name="orders" Grid.Row="4" Background="AliceBlue" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" AutoGenerateColumns="False"  >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn  Header="Select" Binding="{Binding Path=IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}}" ></DataGridCheckBoxColumn>
            <DataGridTextColumn Header="Item Name" Binding="{Binding Path=Name}" ></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

我想编写单击按钮的代码来删除选中复选框的所有行。

    private void btnDelete_Click(object sender, RoutedEventArgs e)
    {
        //Delete logic here

    }

我如何实现这一目标? 注意:我使用的是EntityFramework,而不是ADO。 datagrid绑定到类似Order ObservableCollection<Order>

的可观察集合

3 个答案:

答案 0 :(得分:2)

首先确保DataGrid允许通过SelectionMode

进行多项选择
SelectionMode="Extended"

然后点击按钮,根据视图中的IsSelected绑定从网格中获取所选项目

private void btnDelete_Click(object sender, RoutedEventArgs e) {
    //get selected items
    if (orders.SelectedItems != null && orders.SelectedItems.Count > 0) {
        var toRemove = orders.SelectedItems.Cast<Order>().ToList();
        //Delete logic here
        //...remove items from EF and save

        //Once confirmed remove from items source
        var items = orders.ItemsSource as ObservableCollection<Order>;
        if (items != null) {
            foreach (var order in toRemove) {
                items.Remove(order);       
            } 
        }
    }
}

答案 1 :(得分:1)

Write code behind like this....
        public MainWindow()
        {
            InitializeComponent();
            List<Great> p = new List<Great>();
            p.Add(new Great() { Name = "Good" });
            p.Add(new Great() { Name = "Bad" });
            p.Add(new Great() { Name = "Ugly" });
            orders.ItemsSource = p;

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<Great> SelectedOrders = new List<Great>();
            for (int i = 0; i < orders.SelectedItems.Count; i++)
            {
                SelectedOrders.Add((Great)orders.SelectedItems[i]);
            }
            var kk = orders.ItemsSource as List<Great>;
            foreach (var item in SelectedOrders)
            {
                kk.Remove(item);
            }
            orders.Items.Refresh();
        }

       public class Great
        {
            public string Name { get; set; }
        }

答案 2 :(得分:0)

只需拨打Clear()上的ObservableCollection<Order>方法:

private void btnDelete_Click(object sender, RoutedEventArgs e)
{
    var sourceCollection = orders.ItemsSource as ObservableCollection<Order>;
    if (orders != null)
        orders.Clear();
}