简体   繁体   English

如何从datagrid中删除无效行?

[英]How to delete invalid row from datagrid?

Description of application structure: 申请结构说明:

Language is C# with WPF and MVVM pattern. 语言是带有WPF和MVVM模式的C#。 View is basically a DataGrid for displaying some DataTable values (through ViewModel). View基本上是一个DataGrid,用于显示一些DataTable值(通过ViewModel)。 User is allowed to add, edit and delete rows from the grid. 允许用户从网格中添加,编辑和删除行。 Some value restrictions apply (no nulls, only numeric, etc...) due to database from where values are retrieved and later inserted back. 由于数据库从中检索值并稍后插回,因此会应用一些值限制(无空值,仅限数字等)。

Data modifications can be made directly to DataGrid but there is also a separate dialog for editing and adding new rows. 可以直接对DataGrid进行数据修改,但是还有一个单独的对话框用于编辑和添加新行。 A delete button works in a way that ViewModel finds selected DataGrid rows from DataTable, deletes them and changes are updated automatically to DataGrid as they should. 删除按钮的工作方式是ViewModel从DataTable中找到所选的DataGrid行,删除它们并将更改自动更新为DataGrid。

Problem: 问题:

So I'm having this problem where user attempts to insert invalid data to DataGrid and red exclamation mark appears to indicate that there is a problem with inserted data (validation error I guess?). 所以我遇到这个问题,用户试图将无效数据插入DataGrid,并出现红色感叹号,表明插入数据存在问题(我猜是验证错误?)。 If at this point user wishes to start over and selects invalid row for deletion, he is unable to delete that row as it does not exist in the model but only in DataGrid. 如果此时用户希望重新开始并选择无效行进行删除,则无法删除该行,因为它在模型中不存在但仅在DataGrid中存在。 Attempting to delete invalid DataGridRow directly from DataGrid throws an exception stating that DataGrid is bound to a Model and any modifications should be made there. 尝试直接从DataGrid删除无效的DataGridRow会引发一个异常,指出DataGrid绑定到Model并且应该在那里进行任何修改。

Finally question: 最后问题:

How to delete invalid DataGridRow which is not present in model? 如何删除模型中不存在的无效DataGridRow?

If you implement MVVM pattern then you don't have to do anything except linking changes in your observablecollection to data layer to connect it to DB. 如果实现MVVM模式,那么除了将observablecollection中的更改链接到数据层以将其连接到DB之外,您不必执行任何操作。

Also you may define DataGrid as : 您也可以将DataGrid定义为:

<DataGrid ItemsSource="{Binding Items}" SelectedItem="{Binding ActiveItem}" .../>

Then you may react to PropertyChanged events of Items and ActiveItem in your code, kind of 然后你可以在你的代码中对Items和ActiveItem的PropertyChanged事件作出反应

ActiveItem.PropertyChanged += ... 

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM