在我的Window構造函數InitializeComponents後,我需要創建一個對象並將其綁定到一個數據網格。由於創建對象花費的時間太多,所以窗口需要一段時間才能顯示出來。所以我決定將對象的創建移動到後臺線程,並通過執行dispatcher.invoke來執行綁定,將其「委託回」到UI線程。但是這失敗了。WPF:在UI線程和後臺線程之間傳遞對象
奇怪的是,如果我嘗試設置一個矩形的可見性,我有Dispatcher.invoke裏面的工作,但DataGrid.setbinding沒有!有任何想法嗎?我已經嘗試過與後臺工作者和threadstart相同的事情,但我一直得到相同的錯誤。我無法訪問DataGrid對象,即使它發生在調度程序內調用委託。我確定在理解其工作原理時錯過了一些東西。任何建議將不勝感激。謝謝!
StartupDelegate s = new StartupDelegate(CreateModel);
s.BeginInvoke(delegate(IAsyncResult aysncResult) { s.EndInvoke(aysncResult); }, null);
internal CreateModel()
{
Model d = new Model();
Dispatcher.Invoke(DispatcherPriority.Normal,
new Action<Model>(
delegate(Model d1)
{
mModel = d1; // mModel is a property defined in Window
Binding b = new Binding();
b.Source = mModel;
MainDataGrid.SetBinding(TreeView.ItemsSourceProperty, mainb); // << dies here with - The calling thread cannot access this object because a different thread owns it.
}
}
UPDATE: 結束了使用,將只運行一次一個 dispatchertimer。將綁定代碼放在它的Tick委託中。但我仍然很好奇爲什麼上面的代碼沒有。
我曾嘗試過這種不在xaml中,但只是設置綁定到屬性,屬性爲null。所以代表只有一行mModel = d1。但沒有發生。它不是一個依賴屬性,而是一個實現notifypropertychanged的普通屬性。 – Sharun 2009-07-25 13:06:47