Hi,
I'm using the wpf toolkit datagrid to display an observable collection of AccountViewModels.
The thing is when I delete an account from the grid, I want it removed from the ObservableCollection - to give the user visual feedback, but i want the underlying list of Account models to remain the same, just with an 'IsDeleted' flag set on the Account model.
Then whenever the changes are committed, my service knows which accounts to add/update or delete in the database.
Im subscribing to the CollectionChanged event:
AccountViewModels.CollectionChanged += AccountsChanged;
and then setting the viewmodels' model isdeleted flag to true whenever something is removed:
private void AccountsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (AccountViewModel model in e.NewItems)
{
model.PropertyChanged += accountPropertyChanged;
model.Account.IsNew = true;
}
}
if (e.OldItems != null)
{
foreach (AccountViewModel model in e.OldItems)
{
model.PropertyChanged -= accountPropertyChanged;
model.Account.IsDeleted = true;
}
}
}
but obviously this then removes it from the observable collection. So when I come to commit the changes, there will be no accounts with IsDeleted flag set. i.e. they will have already been removed.
foreach (AccountViewModel acc in m_ViewModel.AccountViewModels)
{
WorkItem workItem = null;
if(acc.Account.IsNew)
workItem = new WorkItem("Saving new account: " + acc.AccountName, "Saving new account to the database", () => Service.AddAccount(acc.Account));
else if (acc.Account.IsDeleted)
workItem = new WorkItem("Removing account: " + acc.AccountName, "Setting account inactive in the database", () => Service.RemoveAccount(acc.Account));
else if(acc.Account.IsDirty)
workItem = new WorkItem("Updating account: " + acc.AccountName, "Updating account in the database", () => Service.UpdateAccount(acc.Account));
workItems.Add(workItem);
}
So does this mean I need to maintain two lists, one list of account models and the other an observable collection of accountviewmodels? This just seems nasty and there must be a better way of doing this.