我有一个包含复选框的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>
答案 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();
}