WPF ComboBox 绑定大集合的性能问题 [英] WPF ComboBox performance problems by binding a large collections

查看:20
本文介绍了WPF ComboBox 绑定大集合的性能问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将大型集合绑定到 ComboBox,但在打开 ComboBox 的弹出窗口时遇到了性能问题.我在互联网上搜索并发现使用 VirtualizingStackPanel 作为项目面板模板可能会有所帮助,但它只是部分帮助.如果我将一个大集合绑定到一个 ComboBox,我可以非常快地打开弹出窗口,那没关系,但是如果之后我将另一个集合绑定到一个 ComboBox 并尝试再次打开弹出窗口,它会变得非常慢.如果您为空的 ComboBox 打开弹出窗口,然后绑定大集合并尝试再次打开弹出窗口,则会发生同样的情况 - 弹出窗口打开需要几秒钟时间.

I'm trying to bind a large collection to a ComboBox and I faced performance problems when opening ComboBox's popup. I searched internet and found that using VirtualizingStackPanel as a items panel template might help, but it helped only partially. If I bind a large collection to a ComboBox, I could open popup very quickly, that's ok, but if after that I bind another collection to a ComboBox and try to open popup again, it becomes very slow. Same is happening if you open popup for an empty ComboBox, then bind large collection and try to open popup again - it takes some seconds before popup opens.

这是 XAML:

<ComboBox Name="cbBlah">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
</ComboBox>

以及绑定重现问题的示例代码:

and the sample code for binding to reproduce the problem:

var list = new List<string>();
for (var i = 0; i < new Random().Next(9000, 10000); i++)
    list.Add(i.ToString());
cbBlah.ItemsSource = list;

我试图让虚拟化堆栈面板看起来像这样:

I tried to make virtualizing stack panel to look like this:

<VirtualizingStackPanel VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling" />

但这无济于事,似乎 VirtualizationMode 被忽略,因此弹出窗口仅第一次打开非常快,然后,每次绑定更改后,它都非常慢.

but it doesn't help, seems VirtualizationMode is ignored so popup opens very fast only first time and then, each time after binding changes, it's very slow.

UPDATE:我想不是每次都绑定新的集合,而是绑定一个 ObservableCollection 一次,然后只是改变它的内容.同样的事情,一旦集合的内容发生变化,打开弹出窗口仍然需要几秒钟:(

UPDATE: I thought about not binding new collection every time, but bind an ObservableCollection once and then just changing its content. Same thing, as soon as content of collection changes, opening a popup still takes several seconds :(

推荐答案

根据此博客:http://vbcity.com/blogs/xtab/archive/2009/12/15/wpf-using-a-virtualizingstackpanel-to-improve-combobox-性能.aspx

我已经用这个代码测试过:

I've tested it with this code:

<ComboBox Name="cbBlah" ItemsSource="{Binding}">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
</ComboBox>

第一次和下次都可以正常工作.没有必要对这些行进行编码:

It works fine for first time and next times. It's not necessary to code these lines:

<VirtualizingStackPanel VirtualizingStackPanel.IsVirtualizing="True" VirtualizingStackPanel.VirtualizationMode="Recycling" />

希望对你有帮助.

这篇关于WPF ComboBox 绑定大集合的性能问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆