Prevent DataGrid Row Deletion

I want to protect some rows of the DataGrid for protection against user deletion, although the CanUserDeleteRows property CanUserDeleteRows set to true .

Is it possible to protect some lines, I hope, through data binding or trigger? The ItemsSource element is bound to ObservableCollection T.

+7
source share
2 answers

If you have a property on related objects that you can use to determine whether the current row can be deleted, such as "IsDeleteEnabled", you can bind the DataGrid CanUserDeleteRows property to SelectedItem.IsDeleteEnabled.

For example,

 <DataGrid Name="dataGrid1" CanUserDeleteRows="{Binding ElementName=dataGrid1, Path=SelectedItem.IsDeleteEnabled}" 
+13
source

Never do this with a DataGrid. Usually, when I need to manage something similar, I use a ListBox and a DataTemplate with a grid inside to give it an idea of ​​the Grid or ListView with the GridView in the template, because they both give you more control over the interaction.

A snapshot in the dark as you bind, you can use the DataGridTemplateColumn.CellEditingTemplate and create your own Delete button / text that is visible or enabled based on the logic in your binding object. Maybe something like this (I have not tested this, but it should be a direction that you can lead)?

 <dg:DataGridTemplateColumn Header="Action"> <dg:DataGridTemplateColumn.CellTemplate> <DataTemplate> <Text Content="Delete" /> </DataTemplate> </dg:DataGridTemplateColumn.CellTemplate> <dg:DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <ButtonEnabled="{Binding Path=IsDeleteEnabled, Mode=OneWay}" Content="Delete" Command="{Binding Path=DeleteMe}" /> </DataTemplate> </dg:DataGridTemplateColumn.CellEditingTemplate> </dg:DataGridTemplateColumn> 

Using this method, since the command is bound to a single object, you may have to raise an event that your ViewModel is processing to remove this line from the ObservableCollection.

Again, not sure if this is the best way, but this is my 10 minute hit. So if this is terrible, please do not drive me away too much.

0
source

All Articles