我有一個WPF窗口,其中包含一個Canvas對象(名稱:canvas)。在WPF線程中添加畫布兒童失敗
當用戶點擊一個按鈕,它會加載大量的數據,這需要較長的時間。
所以,我不想要的UI被凍結,並創建一個後臺線程。
Thread thread = new Thread(new ThreadStart(BuildGraph));
thread.SetApartmentState(ApartmentState.STA);\
thread.IsBackground = true;
thread.Start();
在這個BuildGraph函數中,我加載數據,創建一些形狀,並將這些形狀放入畫布中。該線程必須是STA才能創建這些形狀。
我使用調度更新文本框中進度。他們都很好。
String txt = (String)Dispatcher.Invoke(DispatcherPriority.Send, (DispatcherOperationCallback)delegate { return labelStatus.Content; }, null);
我可以正確獲取標籤內容。
但是,問題是我不能獲得畫布兒童,這是一個UIElementCollection。
所以,這個操作是不成功的。 canvasChildren =(UIElementCollection)Dispatcher.Invoke(DispatcherPriority.Send,new obtainChildrenDelegate(obtainChildren));
而這也失敗
Dispatcher.BeginInvoke(DispatcherPriority.Send, new Action(() => canvas.Children.Add(node)));
什麼錯在這裏的?爲什麼我可以獲得標籤控件,但不是畫布控件?
奇怪的是,我可以直接使用canvas.ActualHeight不分派器的幫助。