【发布时间】:2021-02-03 07:10:49
【问题描述】:
上下文是我想在 ViewModel 中暴露一个ListView ListCollectionView; ViewModel 会缓慢更新 ObservableCollection(填充集合需要几秒钟)。
因此,我想在ObservableCollection 以这种方式更新后更新ListCollectionView:
MyObservableCollection.CollectionChanged += CollectionChanged;
private void CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
MyListCollectionView.AddNewItem(e.NewItems);
MyListCollectionView.CommitNew();
}
我尝试更新ListCollectionView,但即使使用List<> 也失败了。我该怎么做?
[TestClass]
public class ListViewTests
{
private ListCollectionView _sut;
[TestInitialize]
public void Setup()
{
var toadd = new List<int> {};
_sut = new ListCollectionView(toadd);
}
[TestMethod]
public void AddItem()
{
var toadd = new List<int> { 1,2,3 };
_sut.AddNewItem(toadd);
_sut.CommitNew();
}
}
System.InvalidOperationException:此视图不允许使用“AddNewItem”。
更多详情,我如何更新ObservableCollection:
Parallel.ForEach(ShTiffFiles, file =>
{
var sht = new ShutterTiff(file, _aesService); // slow (small Model)
var shtv = new ShutterTiffVignette(sht, _fastCache); // slow (small ViewModel)
lock (_o) // make it thread safe
{
Application.Current.Dispatcher.Invoke(() =>
{
ShutterTiffObservableCollection.Add(shtv);
});
}
});
在 ViewModel 中:
private object _o = new object();
【问题讨论】:
-
添加到 mm8 答案:如果您将
int[]更改为List<int>,var toadd = new List<int> { 1,2,3 }; _sut.AddNewItem(toadd);将不起作用 -
更新后:为什么...为什么要使用
ListCollectionView?而是直接ObservableCollection? ...为什么如果你真的需要使用 LCV 你不使用MyListCollectionView = new ListCollectionView(MyObservableCollection)?那么你不需要设置 CollectionChanged 事件处理程序 -
@Selvin 这是正确的观点。我不需要担心
ListCollectionView,我只需要添加到ObservableCollection。那么AddNewItem是什么? -
@mm8 你是否暗示有几种方法可以更新 ListCollectionView ?
-
@mm8 我确实错过了那句话。不过,在这种情况下,AddNewItem(Object) 是什么?