Wie*_*Pie 1 c# wpf listbox stopwatch datatemplate
我有这样的代码:(将自定义对象的集合加载到内存和列表框项目中)
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.
}
Run Code Online (Sandbox Code Playgroud)
列表框项附加了非常简单的数据模板,只有一个矩形、几种颜色和一个文本块。当我在附加 listBox.ItemsSource 之后放置断点时,它会立即中断。所以看起来 ListBox 正在创建另一个线程并且它正在做一些事情。我无法找到任何更快的方法。
我做错了什么,但我不知道那是什么。请帮忙 ;)。
默认情况下,ListBox 使用 VirtualizingStackPanel 作为 ItemsPanel,这意味着 ItemsSource 可以包含几乎无限数量的项目,而不会影响性能。
在不修改列表框的干净解决方案中尝试此操作。显示百万个项目没有问题
<ListBox x:Name="listBox" />
listBox.ItemsSource = Enumerable.Range(0, 1000000).ToArray();
Run Code Online (Sandbox Code Playgroud)
VirtualizingStackPanel 仅针对当前在滚动查看器中可见的那些项目实例化 DataTemplate。这就是所谓的虚拟化
看起来,你已经以某种方式破坏了虚拟化。原因可能是:
您是否使用任何 wpf 主题或列表框的某些隐式样式?
如果是 ItemsControl,则需要进行一些工作才能使虚拟化工作:虚拟化 ItemsControl?
只是为了确保这是虚拟化问题,请尝试用最简单的可能 - 空矩形替换您的数据模板,甚至删除它。希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
2140 次 |
| 最近记录: |