How can I do CanDelete validation on ObservableCollection<T>?

219 views Asked by At

I am binding ObservableCollection to xamdatagrid via source property.

<igDP:XamDataGrid DataSource="{Binding Path=MyCollection}" />

One way I can do it is to use

_items.CollectionChanged += ItemsChanged

But this seems too late because items are already removed. Is there any nice solution to it?

Update

Items are deleted manually by user via xamdatagrid.

Thanks

3

There are 3 answers

2
user007 On BEST ANSWER

You shouldn't delete row directly in the Grid, UI is not responsible for performing Business Actions, this should be performed by ViewModel and before that ViewModel should do validation.

AllowDelete="False"

in DataGrid:

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

On View Model you will have DeleteOrderCommand.

If you replace this View with some other technology and new Control does not have delete row option you would use button. So you could still reuse your ViewModel as button would bind to the DeleteOrderCommand or to the method that this command is calling, as well your validation is in ViewModel so it hasn't disappeared when you switched to View in new technology.

UPDATE: You can use CanExecute on DeleteOrderCommand for validation purposes, or if it is more convenient in the Execute method of Command.

0
Andrej B. On

If you are deleting items from UI, you can use CanExecute(object parameter) from ICommand interface

0
Florian Gl On
  1. Solution:

    I think the best way is to remove the items with a Command in your ViewModel. This way you can do the validation in the CanExecute method of your command and it can't be executed if its not valid. You can use InputBindings or EventToCommand to fire a command after user interaction.

  2. Solution

    You could inherit from ObservableCollection and override the RemoveItem-method and do the validation there, but I would recommend doing it the way described above.