我通過DataGrid.ItemSource屬性將IEnumerable集合傳遞給WPF DataGrid。但是當我試圖更改代碼中的集合項時,它不會更新DataGrid。 爲什麼?WPF DataGrid.ItemSource
0
A
回答
3
您需要綁定到實現INotifyCollectionChanged接口的類型,以便它提供數據綁定可用於監視何時添加或刪除項目的事件。這在WPF的最佳類型的ObservableCollection <>,它有一個構造函數會接受你的IEnumerable:
ObservableCollection<string> collection = new ObservableCollection<string>(iEnumerableobject);
dataGrid.ItemSource = collection;
collection.Add("Wibble");
將正常更新。
從您的意見到另一個答案,它看起來像你需要從UI線程內調用添加調用。不知道更詳細的代碼,我不知道爲什麼你需要做到這一點,但讓我們假設你是從一個服務在後臺獲取數據:
private ObservableCollection<string> collection;
public void SetupBindings()
{
collection = new ObservableCollection<string>(iEnumerableobject);
dataGrid.ItemSource = collection;
//off the top of my head, so I may have this line wrong
ThreadPool.Queue(new ThreadWorkerItem(GetDataFromService));
}
public void GetDataFromService(object o)
{
string newValue = _service.GetData();
//if you try a call add here you will throw an exception
//because you are not in the same thread that created the control
//collection.Add(newValue);
//instead you need to invoke on the Ui dispatcher
if(Dispather.CurrentDispatcher.Thread != Thread.CurrentThread)
{
Dispatcher.CurrentDispatcher.Invoke(() => AddValue(newValue));
}
}
public void AddValue(string value)
{
//because this method was called through the dispatcher we can now add the item
collection.Add(value);
}
正如我說的,我不有一個IDE可以交付,所以這可能不會編譯,但會指向正確的方向。
根據你在後臺做什麼確切的任務,可能有更好的方法來做到這一點。我上面的示例使用backgroundworker將更容易實現,因此您可能也想閱讀該示例。
1
您需要改爲使用ObservableCollection。 (或使自己的類包裝的收集和實現INotifyPropertyChanged接口)
0
您也可以使用實現INotifyCollectionChanged界面的集合,如果你不能使用的ObservableCollection出於某種原因...
相關問題
- 1. 更改DataGrid.ItemSource的工作方式
- 2. 清除wpf中的datagrid值
- 3. 在WPF中編輯DataGrid
- 4. 內存映射文件到WPF網格
- 5. 獲取WPF數據網格上下文菜單中單擊行
- 6. WPF -
- 7. WPF
- 8. wpf
- 9. wpf
- 10. WPF Datagrid WPF樣式問題
- 11. WPF:圖像單擊WPF
- 12. WPF 3.5 SP1 V/s WPF 4.0
- 13. 在WPF中Mousemoving Usercontrol WPF
- 14. 如何將ObservableCollection類綁定到WPF中的DataGrin
- 15. 如何讓WPF DataGrid在DataGridTextColumn中使用類的成員變量?
- 16. WPF ResourceDictionaries
- 17. 在WPF
- 18. WPF togglebutton
- 19. 在WPF
- 20. 在WPF
- 21. WPF DependencyPropeprty
- 22. 在WPF
- 23. ControlsCollection WPF
- 24. 在WPF
- 25. 在WPF
- 26. WPF SharedResourceDictionary
- 27. 在WPF
- 28. 在WPF
- 29. 在WPF
- 30. 在WPF
+1爲男人,而不僅僅是在答案中使用「Wibble」。我說得好! 。 。 。是的,今天下午我感覺有點奇怪。 。 。 – 2009-06-11 16:08:44
我更改爲ObservableCollection,但它仍然沒有區別。這是顯示正確的數據,當我第一次啓動一個程序,但從未更新網格後,然後......我做錯了什麼 – Agzam 2009-06-11 16:10:21