【发布时间】:2010-01-26 11:29:10
【问题描述】:
我正在使用 wpf 工具包数据网格来显示 AccountViewModel 的可观察集合。
问题是当我从网格中删除一个帐户时,我希望将其从 ObservableCollection 中删除 - 为用户提供视觉反馈,但我希望 Account 模型的基础列表保持不变,只需使用“IsDeleted”在 Account 模型上设置的标志。
然后,无论何时提交更改,我的服务都知道要在数据库中添加/更新或删除哪些帐户。
我正在订阅 CollectionChanged 事件:
AccountViewModels.CollectionChanged += AccountsChanged;
然后在删除某些内容时将视图模型的模型 isdeleted 标志设置为 true:
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;
}
}
}
但显然这会将其从可观察集合中删除。因此,当我提交更改时,将没有设置 IsDeleted 标志的帐户。即它们已经被删除了。
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);
}
这是否意味着我需要维护两个列表,一个是帐户模型列表,另一个是可观察的帐户视图模型集合?这看起来很讨厌,必须有更好的方法来做到这一点。
【问题讨论】:
标签: wpf viewmodel observablecollection