我可以在集合更改事件上回滚集合更改吗? [英] Can I rollback collection changes on collection changed event?
问题描述
我有 2 个列表视图......并在它们之间添加/删除按钮.
I have 2 list views...and add/remove buttons between them.
关于视图模型中列表视图集合的集合更改事件,我可以回滚特定条件的更改吗?
On collection changed event of a list-view-collection in viewmodel, can i rollback the changes for a particular condition ?
推荐答案
您可以处理 CollectionChanged
事件以备份(通过 VM 或其他方式)旧值(请参阅 NotifyCollectionChangedEventArgs.OldItems
属性)并在需要时取回它们即当用户点击撤消"等
You could handle the CollectionChanged
event of the ObservableCollection
to backup (via the VM or whatever) the old values (see NotifyCollectionChangedEventArgs.OldItems
property) and get them back when needed i.e. when user clicks 'Undo' etc.
更新参考以下评论:
如果您确实希望使用 CollectionChanged
事件处理程序回滚集合,请创建一个标志,您可以在其中从递归调用(未使用多线程应用程序测试)中转义处理程序,这里是一个简单的例子,你可以轻松地调整它以适应你的 V/VM.
If you do want to rollback the collection from withing the CollectionChanged
event-handler, create a flag where you escape the handler from a recursive call (not tested with multi-threaded application), here is a simple example, you can easily tweak it to fit in your V/VM.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
var x = new ObservableCollection<string>();
x.CollectionChanged +=
new NotifyCollectionChangedEventHandler(x_CollectionChanged);
x.Add("asdf");
x.Remove("asdf");
}
bool rollingBack = false;
void x_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (rollingBack) return;
if (e.Action == NotifyCollectionChangedAction.Remove)
{
if (e.OldItems.Contains("asdf"))
{
var oc = (ObservableCollection<string>)sender;
rollingBack = true;
oc.Add("asdf");
rollingBack = false;
}
}
}
这篇关于我可以在集合更改事件上回滚集合更改吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!