我在单独的任务中收集数据,我想使用 ObservableCollection<>
将结果数据绑定(bind)到 GUI 组件.所以我的代码是这样的:
private ObservableCollection<MyItem> _items;
public ObservableCollection<MyItem> Items
{
get { return _items; }
set
{
if (_items.Equals(value))
{
return;
}
_items = value;
RaisePropertyChanged("Items");
}
}
private void LoadData()
{
Task task = Task.Factory.StartNew(() =>
{
ObservableCollection<MyItem> itms = _htmlParser.FetchData(...);
Dispatcher.CurrentDispatcher.Invoke((Action)delegate
{
Items = itms;
});
});
}
数据是从执行一些 HTTP 请求的组件中获取的。我得到的错误是:
Must create DependencySource on same Thread as the DependencyObject.
我正在使用 MVVM Light 工具包框架。我还尝试将结果作为消息发送,但最终出现了相同的错误消息。有什么想法或指示吗?
编辑:这是问题所在:
public class MyItem
{
public string Id { get; set; }
public string Name { get; set; }
public BitmapImage Image { get; set; } // <--- A big No No because it inherits from the DependencyObject
public Uri Uri { get; set; }
}
我更改了 BitmapImage
到 byte[]
数据类型。
最佳答案
你能不能尝试将 Dispatcher.CurrentDispatcher
替换成 Application.Current.Dispatcher
虽然不确定
关于c# - 如何处理 MVVM 中并行任务的 ObservableCollection<> 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3625581/