开发者

canceling remove action - NotifyCollectionChangedAction

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 (NavigationAct开发者_如何学编程ions.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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜