我正在一個單獨的任務中收集數據,並且我想要使用ObservableCollection<>
將結果綁定到GUI組件。所以我的代碼如下所示:如何處理MVVM中並行化任務的ObservableCollection <>結果?
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[]
數據類型。
如果您的任務應該在後臺進行,以便它不會鎖定UI,那麼看起來很奇怪,您所做的第一件事是回調到UI線程 - 這不會阻止所有UI輸入_htmlParser正在獲取數據? – 2010-09-02 09:26:53
@馬丁,你正在提出一個非常好的觀點。當我把問題放在一起時,我很快簡化了代碼。我現在用更好的代碼流更新了這個問題。 – 2010-09-02 10:04:02