views:

34

answers:

1

I am using the following code in my viewmodel to delete items out of a collection:

UnitMeasureCollection.CollectionChanged += new NotifyCollectionChangedEventHandler(ListOfUnitMeasureCollectionChanged);

void ListOfUnitMeasureCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.Action == NotifyCollectionChangedAction.Remove)
    {
        if (NavigationActions.DeleteConfirmation("Delete Item.", "Are you sure you want to delete this item? This action cannot be undone."))
        {
            foreach (UnitMeasureBO item in e.OldItems)
            {
                UnitMeasureBO unitMeasureBO = item as UnitMeasureBO;
                bool inUse = unitMeasureRepository.UnitMeasureInUse(unitMeasureBO.UnitMeasureValue);
                if (inUse == true)
                {
                    NavigationActions.ShowError("Cannot delete item", "This item cannot be deleted because it is used elsewhere in the application.");
                }
                else
                {
                    unitMeasureRepository.DeleteUnitMeasure(unitMeasureBO.UnitMeasureValue);
                }
            }
        }
    }
}

I have a datagrid that is bound to the collection. I am wondering if there is anyway of canceling the remove action based on the confirmation prompt? I noticed NotifyCollectionChangedEventArgs does not have a cancel method. What happens is when a user deletes an item out of the datagrid but chooses 'no' on the confirmation, the item is still removed from the datagrid. It isn't deleted from the database and if the datagrid is refreshed it will appear again. I am using the mvvm pattern and I prefer to do this without having to code my datagrid. Any help is appreciated.

+1  A: 

Well, you can't cancel a remove action during a CollectionChanged event.

My suggestion: if you're using MVVM, you should have a DeleteCommand somewhere that is triggered when the DeleteKey is pressed in the DataGrid. In the Execute() method of this command, you should:

  1. Ask the confirmation.
  2. If user chooses yes, then remove the item from the collection. This removal should directly be reflected on the DataGrid.
  3. If user chooses no, do nothing.

This means, though that the DataGrid.CanUserDeleteRows is set to False since you basically have to control when the rows get deleted.

Hope this helps.

karmicpuppet
That's what I thought. I like your idea about the delete command though. Thanks!
steveareeno