取消删除操作 - NotifyCollectionChangedAction

ste*_*eno 3 wpf datagrid mvvm inotifycollectionchanged

我在viewmodel中使用以下代码从集合中删除项目:

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);
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个绑定到集合的数据网格.我想知道是否有根据确认提示取消删除操作?我注意到NotifyCollectionChangedEventArgs没有取消方法.当用户从数据网格中删除某个项目但在确认中选择"否"时,该项仍然会从数据网格中删除.它不会从数据库中删除,如果刷新数据网格,它将再次出现.我正在使用mvvm模式,我更喜欢这样做,而无需编写我的数据网格.任何帮助表示赞赏.

ASa*_*nch 6

好吧,你不能在CollectionChanged事件期间取消删除操作.

我的建议:如果你正在使用MVVM,那么当在DataGrid中按下DeleteKey时,你应该有一个DeleteCommand.在此命令的Execute()方法中,您应该:

  1. 询问确认.
  2. 如果用户选择"是",则从集合中删除该项.此删除应直接反映在DataGrid上.
  3. 如果用户选择否,则不执行任何操作.

这意味着,尽管DataGrid.CanUserDeleteRows设置为False,因为您基本上必须控制何时删除行.

希望这可以帮助.