I have a datagrid with a delete icon as one column and update icon as another column. On click of update, the first cell is set on focus.
On click on delete I want to delete that selected row, but I get the error "Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead." with the following code:
XAML:
<DataGrid Name="grdList" Margin="3,16,0,5" RowHeight="30" ColumnWidth="*"
ItemsSource="{Binding List,Mode=TwoWay}" Width="434"
AutoGenerateColumns="False"
CanUserAddRows="False" AlternatingRowBackground="#FFB9BBFF">
<DataGrid.Columns>
<DataGridTextColumn MinWidth="0" Header="Property"
Binding="{Binding Path=Property}"/>
<DataGridTemplateColumn Header="Update" MinWidth="50" MaxWidth="50">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="EventSetter_OnHandler"/>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="Icons/Update.jpg"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Delete" MinWidth="50" MaxWidth="50">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<EventSetter Event="PreviewMouseLeftButtonDown"
Handler="EventSetter_OnHandler"/>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Image Source="Icons/Delete.jpg"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
C#:
private void EventSetter_OnHandler(object sender, MouseButtonEventArgs e)
{
object source = e.OriginalSource;
if (source.GetType() == typeof(Image))
{
grdList.IsReadOnly = false;
selectedRow = FindParent<DataGridRow>(sender as DependencyObject);
if (((DataGridCell)sender).Column.Header.ToString().ToUpperInvariant() == "DELETE")
{
grdList.Items.Remove(selectedRow);
}
else
{
DataGridCellsPanel panel = FindVisualChild<DataGridCellsPanel>(selectedRow);
DataGridCell dgc = panel.Children[0] as DataGridCell;
dgc.Focus();
grdList.BeginEdit();
e.Handled = true;
}
}
}
Also How to add the delete function with the "Delete" key together with the click on the delete cell.