![](/img/trans.png)
[英]WPF ReactiveUI binding Listbox.ItemsSource to ReadOnlyObservableCollection not working
[英]WPF ListBox.ItemsSource = ObservableCollection - takes a long time to load
我有這樣的代碼:(將自定義對象的集合加載到內存和ListBox項中)
public class Product : INotifyPropertyChanged
{
// these four doesn't matter, just Product's simple data
public string nDB_No { get; set; }
public string fdGrp_Cd { get; set; }
public string long_Desc { get; set; }
public int refuse { get; set; }
// I do not load this Collection right away, only after explicit call
public ObservableCollection<Ingredient> ingredients { get; set; }
public Product() {sets all null}
public static ObservableCollection<Product> LoadProductsFromList(List<string> productList) {gets products data from SQLServer DB}
// and other methods irrelevant here
}
private void buttonCreate_Click(object sender, RoutedEventArgs e)
{
ObservableCollection<Product> productCollection = new ObservableCollection<Product>();
List<string> productList = getProductsNamesFromDB();
var watch = Stopwatch.StartNew();
productCollection = LoadProductsFromList(productList);
watch.Stop();
MessageBox.Show(watch.ElapsedMilliseconds);
// At this point there is about 700-800ms - that's ok, there's over 8000 records in DB
watch = Stopwatch.StartNew();
listBox.ItemsSource = productCollection;
watch.Stop();
MessageBox.Show(watch.ElapsedMilliseconds);
// At this point watch shows only about 500ms but it takes over 10 seconds
//to load the ListBox with data and to show the MessageBox.
}
listBox項具有非常簡單的DataTemplate,僅包含一個Rectangle,少量顏色和一個TextBlock。 當我在連接listBox.ItemsSource之后放置BreakPoints時,它會立即中斷。 這樣看來,ListBox正在創建另一個線程,並且正在執行某些操作。 我無法彌補任何更快的方式。
我做錯了什么,但我不知道那是什么。 請幫忙 ;)。
默認情況下,ListBox使用VirtualizingStackPanel作為ItemsPanel,這意味着ItemsSource可以包含幾乎無限量的項目,而不會影響性能 。
嘗試使用干凈的解決方案,而無需修改列表框。 它顯示了無數個項目
<ListBox x:Name="listBox" />
listBox.ItemsSource = Enumerable.Range(0, 1000000).ToArray();
VirtualizingStackPanel僅實例化那些當前在scrollviewer中可見的項目的DataTemplate。 叫做虛擬化
看來,您已經以某種方式破壞了虛擬化。 原因可能是:
您是否使用任何wpf主題或列表框的某些隱式樣式?
如果使用ItemsControl,則需要做一些工作才能使虛擬化工作: 虛擬化ItemsControl?
為了確保這是虛擬化問題,請嘗試以最簡單的方式替換您的數據模板-空矩形,甚至刪除它。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.