A
A
AndNovak2016-11-10 21:03:03
WPF
AndNovak, 2016-11-10 21:03:03

How to delete selected row in datagrid?

Please tell me how to delete the selected row in dataGrid using ViewModel. Deletion should happen at the click of a button.
Data to dataGird is bound like this

<DataGrid  x:Name="products"  CanUserDeleteRows="False" 
                           AutoGenerateColumns="False" VerticalAlignment="Top" Margin="22,0,0,0" 
                           Height="300">

products get in ViewModel
public BindableCollection<Product> products { get; private set;}
        public MainViewModel()
        {
            db = new Context();
            products = new BindableCollection<Product>(db.Product);       
        }

As far as I understand, I need to create a command using the ICommand interface and add it to the View, but I still don’t understand how to implement this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tex0, 2016-11-11
@AndNovak

In the model, you should have properties: -
a collection of items (Items, you have these products)
- the current selected item (CurrentSelectedItem)
- a command to delete (DeleteRowCommand . I think the simplest implementation of the ICommand interface will suit you, you can find an example yourself, since there are a lot of them on open spaces of these your Internets)
in the same place in the model, file the method for deleting the selected element

public void DeleteCurrentSelected()
{
    if (CurrentSelectedItem != null)
        Items.Remove(CurrentSelectedItem);
}

initialize the command (with an action that performs your delete function) directly in the model constructor (for your task, I think it’s normal)
bind it to the DataGrid like this
bind the command to the delete button like this:
apparently you are a beginner, so I advise you to study the topic of bindings better in WPF

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question