问题
I have a DataGrid which contains informations about products, like NAME and PRICE, Items could be added or removed from DataGrid by Pressing DEL Key down (Remove case).
I am using ObservableCollection as DataGrid source, and it looks like this:
ObservableCollection<ProductTemporary> result = ProductsTempController.Instance.SelectAll();
Also there is button on my Window which is keeping sum of my product's prices updated all the time, when item is added sum is increased, when item is removed sum is decreased and stuffs like that..
In my case I have issue with removing items from my Collection, well, as I said I am doing it by pressing DEL key so here is my code:
if (e.Key == Key.Delete)
{
if (dataGridProducts.SelectedItem != null)
{
ProductTemporary tempItem = (ProductTemporary)dataGridProducts.SelectedItem;
ProductTemporaryController.Instance.Delete(tempItem.Id);
UpdateTotalAmount();
}
}
public void UpdateTotalAmount()
{
double sum = 0;
foreach (var item in result)
{
sum += Convert.ToDouble(item.TotalAmount);
}
btnTotal.Content = string.Format("{0:0.00}", sum) + " " + EUR;
}
As it is possible to see, first I am removing item from database, ObservableCollection will take care to remove it from UI, but I am still having issue in this case:
Lets say there are 2 items on datagrid, when users press del, item will be removed from database but method UpdateTotalAmount(); will be called right after that, and in my Collection there will be two items and I will see incorect Total sum..
So probably I am not doing this UpdateTotalAmount calling on right place or smth like that,
I also thought about this solution:
In stored procedure which is removing item I could send back sum of total items from database, so in that case I dont need to loop any collection to do smth like that, but I think it is not good practice?
Thanks guys, Cheers
回答1:
Instead of calling the Delete
and UpdateTotalAmount
methods in your event handler you could handle the CollectionChanged
event of the ObservableCollection
and remove the item from the database when it is removed from the collection:
ObservableCollection<ProductTemporary> result = new ObservableCollection<ProductTemporary>();//ProductsTempController.Instance.SelectAll();
result.CollectionChanged += (ss, ee) =>
{
if(ee.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove
&& ee.OldItems !=null && ee.OldItems.Count > 0)
{
ProductTemporary removedItem = ee.OldItems[0] as ProductTemporary;
ProductTemporaryController.Instance.Delete(removedItem.Id);
UpdateTotalAmount();
}
};
Then you don't need any PreviewKeyDown
event handler at all.
来源:https://stackoverflow.com/questions/42586271/issue-with-removing-item-from-observablecollection-i-am-doing-something-wrong