防止 DataGrid 行被删除
尽管属性 CanUserDeleteRows
设置为 true
,但我希望保护 DataGrid 的某些行不被用户删除。
是否有可能通过数据绑定或触发器来保护某些行? ItemsSource 绑定到 T 的 ObservableCollection。
I want to protect some rows of a DataGrid to be protected from deletion by the user, although the property CanUserDeleteRows
is set to true
.
Is there a possibility to protect some rows, hopefully through a databinding or a trigger? The ItemsSource is bound to an ObservableCollection of T.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果绑定对象上有一个可用于确定是否可以删除当前行的属性(如“IsDeleteEnabled”),则可以将 DataGrid 的 CanUserDeleteRows 属性绑定到 SelectedItem.IsDeleteEnabled。
例如,
If you have a property on your bound objects that can be used to determine if the current row can be deleted , like 'IsDeleteEnabled', then you can bind the DataGrid's CanUserDeleteRows property to SelectedItem.IsDeleteEnabled.
For example,
从未使用 DataGrid 这样做过。通常,当我需要控制这样的东西时,我使用 ListBox 和带有 Grid 的 DataTemplate 来给它一个 Grid 或带有 GridView 的 ListView 模板的想法,因为它们都可以让您更好地控制交互。
在黑暗中拍摄,因为您正在绑定,所以您可以使用 DataGridTemplateColumn.CellEditingTemplate 并制作您自己的删除按钮/文本,该按钮/文本是可见的或基于绑定对象中的逻辑启用。也许是这样的(我没有测试这个,但它应该是你可以前进的方向)?
使用此方法,由于命令绑定到单个对象,您可能必须引发屏幕的 ViewModel 处理的事件才能从 ObservableCollection 中删除该行。
再次强调,不确定这是否是最好的方法,但这是我 10 分钟的尝试。所以,如果这很可怕,请不要对我投太多反对票。
Never done this with a DataGrid. Usually, when I need to control something like this, I use a ListBox and a DataTemplate with a Grid within to give it the idea of a Grid or a ListView with a GridView in the template because they both give you more control over the interaction.
A shot in the dark, since you're binding, you could use a DataGridTemplateColumn.CellEditingTemplate and make your own Delete button/text which is visible or enabled based off logic within your binding object. Maybe something like this (I didn't test this, but it should be a direction you can head)?
Using this method, since the command is bound to the individual object, you would probably have to raise an event your screen's ViewModel handles to remove that row from the ObservableCollection.
Again, not sure if this is the best way, but it's my 10 minute stab at it. So if it's horrible, please don't vote me down too much.