您無法從後臺工作人員訪問UI控件。您通常在調用BackgroundWorker.RunWorkerAync()之前將IsBusy設置爲true,然後在BackgroundWorker.RunWorkerCompleted事件處理程序中將IsBusy設置爲false。 Seomthing像:
Backgroundworker worker = new BackgroundWorker();
worker.DoWork += ...
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
IsBusy = false;
};
IsBusy = true;
worker.RunWorkerAsync();
您可以使用調度程序將項目添加到您的ObservableCollection而在DoWork的事件hanlder。
編輯:這裏是完整的解決方案
private void Button_Click(object sender, RoutedEventArgs e)
{
//on UI thread
ObservableCollection<string> collection;
ThreadStart start = delegate()
{
List<string> items = new List<string>();
for (int i = 0; i < 5000000; i++)
{
items.Add(String.Format("Item {0}", i));
}
System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
{
//propogate items to UI
collection = new ObservableCollection<string>(items);
//hide indicator
_indicator.IsBusy = false;
}));
};
//show indicator before calling start
_indicator.IsBusy = true;
new Thread(start).Start();
}
我編輯我的回答給您提供一個解決方案。 –