Mercer
Mercer

Reputation: 43

How to deleted selected items in a datagrid bound to an object

I have a command button defined as:

<r:RibbonButton Command = "{StaticResource cmdRemoveCustomer}" Label="Remove Customer"  
CommandParameter="{Binding}" DataContext="{Binding ElementName=dataGridCustomers,
Path=SelectedItems}"  />

And a datagrid

<DataGrid AutoGenerateColumns="False" Height="394" HorizontalAlignment="Left" 
x:Name="dataGridCustomers" VerticalAlignment="Top" Width="803" >
<DataGrid.Columns>

Now I am trying to delete the selected items

public class RibbonRemoveCustomer : ICommand
{
    public void Execute(object parameter)
    {

        // ??? How to remove selected customers?


    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

I tried removing items from the datagrid directly, but get an error stating I should remove the items from the ItemsSource. The datagrid is bound to an observablecollection via code.

  dataGridTrackCustomers.ItemsSource = Customers;

How can I delete all of the selected customers in the datagrid from the Customers object using the RibbonRemoveCustomer command?

Upvotes: 0

Views: 1852

Answers (1)

blindmeis
blindmeis

Reputation: 22445

if you do your commandparameter binding like you did, you should get a IList as parameter. the following code is for DataTable ItemsSource if you dont have DataTables post some code and the type of the "object parameter".

public void Execute(object parameter)
{

    var toDelete= (IList)parameter;//<-- Datagrid.SelectedItems
    var collection = toDelete.Cast<DataRowView>();
    var list = new List<DataRowView>(collection);

    foreach(var item in list)
    {
       item.Row.Delete();
    }
 }

Upvotes: 2

Related Questions