2017-07-12 104 views
0

我有一個DataGrid包含一個複選框。我想通過單擊刪除按鈕來刪除複選框被選中的DataGrid中的所有行。我的數據網格的XAML如下所示。使用複選框和刪除按鈕從WPF Datagrid中刪除多行

<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允許通過SelectionMode

SelectionMode="Extended" 

多選擇,那麼按鈕單擊獲取基礎上,從網格中選定的項目勢必類型訂單的可觀察集合像ObservableCollection<Order>

+0

什麼是當前的行爲基於你已經嘗試了什麼是預期的行爲。如果複選框被正確綁定,那麼它只是獲取'SelectedItems'並將其從集合中移除的問題。 – Nkosi

+0

也許代碼片段可以提供幫助。我如何獲得檢查的行。 – KMarto

回答

1

第一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
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; } 
     } 
0

上只需調用Clear()方法ObservableCollection<Order>

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