18

I have a datagrid and a view model that has an Observable collection of "Person" class which serves as ItemSource for the datagrid.

The Datagrid has two text columns "FirstName" and "LastName"

The datagrid has "CanUserAddRows" and "CanUserDeleteRows" set to true. So the user can add new rows and delete them by using the delete button.

When the user tries to delete a row, i want to validate if he can delete that or not. If he can delete it it will be deleted else the error will be shown and the row cannot be deleted. Something like we have in relay command

New RelayCommand(parm => this.DeletePerson(parm),this.CanDeletePerson(parm)

Is this possible ? If so how ?

  • Girija
Shankar
  • 841
  • 1
  • 13
  • 39

2 Answers2

36

Try setting your DataGrid to ...

CanUserDeleteRows="False" SelectedItem="{Binding SelectedPerson, Mode=TwoWay}"

and adding ...

<DataGrid.InputBindings>
    <KeyBinding Key="Delete" Command="{Binding DeletePersonCommand}" />
</DataGrid.InputBindings>

Add SelectedPerson to your VM and perform your delete validation based on the SelectedPerson in the DeletePersonCommand (ICommand) Execute or CanExecute and remove the item from the ObservableCollection if validation passes.

KornMuffin
  • 2,887
  • 3
  • 32
  • 48
  • 5
    Its worth noting that the grid eats the delete key even if CanUserDelete rows is false, so you can't put the keybinding in a wrapping element. – DanH Jun 14 '13 at 07:58
  • Wow, this is really the perfect solution, after I bound the key to a customized command in my viewmodel, it works perfectly and avoided code behind. I've seen other solutions, but by far this one is the best! – RainCast Mar 10 '15 at 08:02
  • 4
    You can also pass the selected item as a command parameter if you don't want additional bindings: `` – pinki May 12 '15 at 13:51
  • 1
    Why do you need to set CanUserDeleteRows="False" ? – Emran Hussain Jan 19 '16 at 06:00
  • 1
    If True the DataGrid will remove the row w/o performing the validation. By setting to False the VM will handle removing the item from the collection (if it passes the validation) – KornMuffin Jan 19 '16 at 12:29
  • @DanH what do you mean here? The above code works - pressing the ``Delete`` key will result in ``DeletePersonCommand`` being executed. – Conrad Jan 25 '16 at 20:18
1

Bind a property to CanUserDeleteRows.

XAML:

CanUserDeleteRows="{Binding UserCanDelete}"

ViewModel:

    public bool UserCanDelete
    {
        get
        {
            // return a value based on the currently selected item and business rules
        }
    }

Make sure you're raising a PropertyChanged event for this property somewhere, where you do that would depend on the other data changes that affect your return value.

Denise Skidmore
  • 2,286
  • 22
  • 51