如何解决WPF ListView SelectedItems性能不佳的问题? [英] How can I get around this poor WPF ListView SelectedItems performance?

查看:64
本文介绍了如何解决WPF ListView SelectedItems性能不佳的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码(它在WPF ListView中搜索所有匹配项,然后选择所有匹配项):

Here is my code (it searches a WPF ListView for all matches and then selects all of them):

            public bool FindAll(LogFilter filter, bool matchCase)
            {
                lastLogFilter = filter;
                lastMatchCase = matchCase;
                MatchSearcher quickSearchSearcher = new MatchSearcher(filter, !matchCase);
                bool foundOnce = false;
                Stopwatch watch = new Stopwatch();
                watch.Start();
                var query = from x in listView.Items.Cast<LogRecord>() where quickSearchSearcher.IsMatch(x, false) select x;
                watch.Stop();
                Console.WriteLine("Elapsed milliseconds to search: {0}.", watch.ElapsedMilliseconds);
                if (query.Count() > 0)
                {
                    foundOnce = true;
                    listView.SelectedItems.Clear();
                    watch.Restart();
                    foreach (LogRecord record in query)
                    {
                        listView.SelectedItems.Add(record);
                    }
                    watch.Stop();
                    Console.WriteLine("Elapsed milliseconds to select: {0}.", watch.ElapsedMilliseconds);
                    listView.ScrollIntoView(query.First());
                }
                return foundOnce;
            }

以下是包含10,000个ListView项目的结果:

Here are the results with 10,000 ListView items:

Elapsed milliseconds to search: 0.
Elapsed milliseconds to select: 36385.

因此,很明显,我的问题出在循环中:

So, clearly my problem is with the loop:

foreach (LogRecord record in query)
{
    listView.SelectedItems.Add(record);
}

我觉得必须有一种更好的方法来添加到选定项目列表中,或者至少在已设置所有选定项目之前,阻止列表中的数据模板更新(或类似的操作).尝试在WPF ListView中以编程方式选择多个项目时,有什么方法可以获得更好的性能?

I feel like there must be a better way to add to the selected items list, or at least block data template updates (or something like that) on the list until all selected items have been set. Is there any way to get better performance when trying to select multiple items programmatically in a WPF ListView?

推荐答案

您可以将

Instead of adding selected items one by one to the SelectedItems property, you may call the SetSelectedItems method. Unfortunately the method is protected, so you have to create a derived ListBox that makes it publicly available:

public class MyListView : ListView
{
    public void SelectItems(IEnumerable items)
    {
        SetSelectedItems(items);
    }
}

这篇关于如何解决WPF ListView SelectedItems性能不佳的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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