我有两个CollectionViewSource实例:
<FrameworkElement.Resources>
<CollectionViewSource x:Key="currentImages" Source="{Binding ImageFiles}" />
<CollectionViewSource x:Key="toDeleteImages" Source="{Binding ImageFiles}" />
</FrameworkElement.Resources>
两者都绑定到相同的ObservableCollection<ImageFileDetails>
(在视图模型的ImageFiles
属性上):
// implements INPC via Fody.PropertyChanged
[AddINotifyPropertyChangedInterface]
public class ImageFileDetails {
public string Path { get; set; }
public bool ToDelete { get; set; }
}
两个CollectionViewSources之间的区别在于过滤器:
(Resources("currentImages") as CollectionViewSource).Filter += (s,e) =>
e.Accepted = !e.Item<ImageFileDetails>().ToDelete;
(Resources("toDeleteImages") as CollectionViewSource).Filter += (s, e) =>
e.Accepted = e.Item<ImageFileDetails>().ToDelete;
我现在有两个DataGrids,每个DataGrids绑定到一个CollectionViewSources。我希望能够在其中一个DataGrids上按下DELETE键,让项目移动到另一个。该项目实际上不应该从集合中删除,而应该切换ToDelete
属性 - 从true
到false
,从false
到{{1} }。
我尝试处理true
上的CollectionChanged
事件并重新添加已从集合中删除的项目:
ObservableCollection
但是失败了:
System.InvalidOperationException:&#39;在CollectionChanged事件期间无法更改ObservableCollection。&#39;
如何取消收藏中的项目?
答案 0 :(得分:0)
我最终使用PreviewKeyDown
事件;在CollectionViewSource刷新后,选择移动到下一个项目:
KeyEventHandler deleteHandler = (s, e) => {
if (e.Key != Delete) { return; }
if (Modifiers.HasFlag(Alt) || Modifiers.HasFlag(ModifierKeys.Control) || Modifiers.HasFlag(Shift)) { return; }
e.Handled = true;
var dg = s as DataGrid;
var ifd = dg.SelectedItem as ImageFileDetails;
ifd.ToDelete = !ifd.ToDelete;
//even though INPC is implemented on ImageFileDetails, the changes aren't noticed by the
//CollectionViewSource
cvsCurrentImages.View.Refresh();
cvsToDeleteImages.View.Refresh();
dg.Focus();
};