我有一個ObservableCollection<Customer>()
和出於測試的目的,我有簡單的循環,添加2,000,000記錄與隨機數字搜索。當我點擊加載客戶,這顯示一個不錯的微調,並正常工作。等待列表框完成呈現WPF
private async void button_Click(object sender, RoutedEventArgs e)
{
bool result = DatabaseMaster.CheckConnection(con);
spinner.Visibility = Visibility.Visible;
spinner.Spin = true;
customers = await Task.Run(()=>DatabaseMaster.GetCustomers());
customerListBox.ItemsSource = customers;
spinner.Visibility = Visibility.Collapsed;
spinner.Spin = false;
}
但是,我有一個文本框用於搜索,並希望搜索客戶並更新視圖。我試圖
然而,這通過調用線程的錯誤,因爲不同的線程擁有它不能訪問該對象。
我嘗試這個,但UI仍然跳轉,因爲它更新項目源。任何想法或我應該學習更多inotifypropertychanged?
private async void search_TextChanged(object sender, TextChangedEventArgs e)
{
spinner.Visibility = Visibility.Visible;
spinner.Spin = true;
customerListBox.Background = Brushes.Gray;
customerListBox.IsEnabled = false;
await this.Dispatcher.BeginInvoke(new Action(() =>
{
customerListBox.ItemsSource = customers.Where(X => X.name.ToLower().Contains(searchTextBox.Text.ToLower()));
}), null);
customerListBox.Background = Brushes.White;
customerListBox.IsEnabled = true;
spinner.Visibility = Visibility.Collapsed;
spinner.Spin = false;
}
執行'Where'在後臺被分配任務,只更新ui線程中的'ItemsSource',當有很多條目時它仍然會閃爍 – NtFreX
請注意,'.Where(...)'實際上並沒有那麼多,如果你想在任務,你需要調用'.Where(...).ToList()'。 – grek40
@ grek40它當我輸入我的文本框時仍然凍結,因爲當它凍結時它甚至不顯示我的微調器? – Bish25