public static void RemoveDataGridItems <Item>(System.Windows.Controls.DataGrid dataGrid, System.Collections.ObjectModel.ObservableCollection <Item> itemsCollection, ItemInsertEmptyPredicate insertEmptyPredicate, ItemRemovePredicate <Item> removePredicate, ItemsRemovedPredicate removedPredicate) { if (dataGrid.SelectedItems.Count < 1) { return; } int[] indexes = new int[dataGrid.SelectedItems.Count]; int i = 0; foreach (var item in dataGrid.SelectedItems) { indexes[i] = dataGrid.Items.IndexOf(item); ++i; } Util.SortDsc(indexes); bool removed = false; foreach (int index in indexes) { if (index + 1 < itemsCollection.Count) { Item item = itemsCollection[index]; removePredicate(item); itemsCollection.RemoveAt(index); removed = true; } } int selectIndex = -1; if (indexes.Length > 0) { selectIndex = indexes[indexes.Length - 1]; } if (removed) { if (selectIndex >= 0 && selectIndex == itemsCollection.Count - 1) { insertEmptyPredicate(selectIndex); } removedPredicate(); } Util.SelectDataGridItem(dataGrid, selectIndex); }
public static void DataGridItemPropertyChanged <Item>(System.Windows.Controls.DataGrid dataGrid, System.Collections.ObjectModel.ObservableCollection <Item> items, Item item, string propertyName, ItemUpdatedPredicate updatePredicate, ItemInsertEmptyPredicate insertEmptyPredicate, ItemRemovePredicate <Item> removePredicate, ItemRemovedPredicate removedPredicate) where Item : VariableItem { int index = items.IndexOf(item); if (index < 0 || index >= dataGrid.Items.Count) { return; } if (propertyName == "Name") { if (item.Name == null || item.Name == "") { if (index < dataGrid.Items.Count - 1) { removePredicate(item); items.RemoveAt(index); removedPredicate(index); if (index > 0) { Util.SelectDataGridItem(dataGrid, index - 1); } } } else { updatePredicate(index); int next_index = index + 1; // insert new empty row if needed if (next_index == items.Count) { insertEmptyPredicate(next_index); } // select current row, move to next one is automatic Util.SelectDataGridItem(dataGrid, index); } } else if (propertyName == "IsEnabled") { updatePredicate(index); } }