解决WPF中DataGrid移除选中项后报错的问题

1、问题描述

DataGrid列表中添加删除按钮,点击后执行下述操作:

ModelList.Remove(item);

这时候会有XAML绑定失败错误:

严重性    计数    数据上下文    绑定路径    目标    目标类型    说明    文件    行    项目
错误    12    null    SelectionUnit    DataGridCell    DataGridCell    找不到源: RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1'

VS输出调试信息:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.DataGrid', AncestorLevel='1''. BindingExpression:Path=SelectionUnit; DataItem=null; target element is 'DataGridCell' (Name=''); target property is 'NoTarget' (type 'Object')

2、问题分析

VS输出的错误信息已经指出了问题所在,即在执行数据项删除后,DataGrid选中行的绑定数据找不到了,这时候只需要将选中行重置即可。

3、问题解决

为DataGrid添加选中项绑定:

SelectedIndex="{Binding SelectedItemIndex}"

点击删除按钮后将选中项索引重置即可:

SelectedItemIndex = -1;
ModelList.Remove(item);
posted @ 2022-11-20 22:00  xhubobo  阅读(640)  评论(0编辑  收藏  举报