[英]How can I do CanDelete validation on ObservableCollection<T>?
I am binding ObservableCollection to xamdatagrid via source property. 我通过源属性将ObservableCollection绑定到xamdatagrid。
<igDP:XamDataGrid DataSource="{Binding Path=MyCollection}" />
One way I can do it is to use 我可以做到的一种方法是使用
_items.CollectionChanged += ItemsChanged
But this seems too late because items are already removed. 但这似乎为时已晚,因为项目已被删除。 Is there any nice solution to it? 有什么好的解决方案吗?
Update 更新
Items are deleted manually by user via xamdatagrid. 用户通过xamdatagrid手动删除项目。
Thanks 谢谢
You shouldn't delete row directly in the Grid, UI is not responsible for performing Business Actions, this should be performed by ViewModel and before that ViewModel should do validation. 您不应该直接在网格中删除行,UI不负责执行业务操作,这应该由ViewModel执行,并且在ViewModel进行验证之前。
AllowDelete="False"
in DataGrid: 在DataGrid中:
<DataGrid.InputBindings>
<KeyBinding Key="Delete" Command="{Binding DeleteOrderCommand}" />
</DataGrid.InputBindings>
On View Model you will have DeleteOrderCommand. 在视图模型上,您将具有DeleteOrderCommand。
If you replace this View with some other technology and new Control does not have delete row option you would use button. 如果您使用其他某些技术替换了该视图,并且新的控件没有删除行选项,则可以使用按钮。 So you could still reuse your ViewModel as button would bind to the DeleteOrderCommand or to the method that this command is calling, as well your validation is in ViewModel so it hasn't disappeared when you switched to View in new technology. 因此,您仍然可以重用ViewModel,因为按钮将绑定到DeleteOrderCommand或此命令正在调用的方法,并且您的验证位于ViewModel中,因此当您以新技术切换到View时,验证并不会消失。
UPDATE: You can use CanExecute on DeleteOrderCommand for validation purposes, or if it is more convenient in the Execute method of Command. 更新:您可以在DeleteOrderCommand上使用CanExecute进行验证,或者在Command的Execute方法中使用起来更方便。
如果要从UI删除项目,则可以从ICommand接口使用CanExecute(object parameter)
Solution: 解:
I think the best way is to remove the items with a Command
in your ViewModel. 我认为最好的方法是在ViewModel中使用Command
删除项目。 This way you can do the validation in the CanExecute method of your command and it can't be executed if its not valid. 这样,您可以在命令的CanExecute方法中进行验证,如果验证无效,则无法执行验证。 You can use InputBindings or EventToCommand to fire a command after user interaction. 您可以在用户交互后使用InputBindings或EventToCommand来触发命令。
Solution 解
You could inherit from ObservableCollection and override the RemoveItem-method and do the validation there, but I would recommend doing it the way described above. 您可以从ObservableCollection继承并覆盖RemoveItem方法并在那里进行验证,但是我建议按照上述方法进行操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.