【问题标题】:Wpf toolkit AutoCompleteBox search on background threadWpf 工具包 AutoCompleteBox 在后台线程上搜索
【发布时间】:2011-06-01 19:26:39
【问题描述】:

我正在使用 WPF 工具包 AutoCompleteBox,它的 itemsSource 是数百万个对象的列表。

AutoCompleteBox 是否用于搜索后台线程,如果没有,我该如何做到。

【问题讨论】:

    标签: wpf multithreading autocompletebox


    【解决方案1】:

    不,它不使用后台线程。您可以在WPF Tookit 中自己阅读源代码。但是,它足够灵活,可以让您自己在后台线程上执行此操作。

    您可以使用这种方法:

    • 处理Populating 事件:取消它,然后使用SearchText 启动后台工作程序
    • 后台工作人员完成后:设置ItemsSource并调用PopulateComplete

    在 MSDN 文档中有一个完整的例子:

    该示例使用异步 Web 服务来填充自动完成数据,但同样的想法也适用于搜索非常大的数据集。后台线程

    更新:

    这是一个在后台线程上进行搜索的完整示例。它包括一秒钟的睡眠来模拟长时间的搜索:

    private class PopulateInfo
    {
        public AutoCompleteBox AutoCompleteBox { get; set; }
        public string SearchText { get; set; }
        public IEnumerable<string> Results { get; set; }
    }
    
    private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e)
    {
        var populateInfo = new PopulateInfo
        {
            AutoCompleteBox = sender as AutoCompleteBox,
            SearchText = (sender as AutoCompleteBox).SearchText,
        };
        e.Cancel = true;
        var ui = TaskScheduler.FromCurrentSynchronizationContext();
        var populate = Task.Factory.StartNew<PopulateInfo>(() => Populate(populateInfo));
        populate.ContinueWith(task => OnPopulateComplete(task.Result), ui);
    }
    
    private PopulateInfo Populate(PopulateInfo populateInfo)
    {
        var candidates = new string[] {
            "Abc",
            "Def",
            "Ghi",
        };
        populateInfo.Results = candidates
            .Where(candidate => candidate.StartsWith(populateInfo.SearchText, StringComparison.InvariantCultureIgnoreCase))
            .ToList();
        Thread.Sleep(1000);
        return populateInfo;
    }
    
    private void OnPopulateComplete(PopulateInfo populateInfo)
    {
        if (populateInfo.SearchText == populateInfo.AutoCompleteBox.SearchText)
        {
            populateInfo.AutoCompleteBox.ItemsSource = populateInfo.Results;
            populateInfo.AutoCompleteBox.PopulateComplete();
        }
    }
    

    【讨论】:

    • 谢谢,但不知何故它对我不起作用。为什么他们更新了整个 ItemsSource 而不仅仅是下拉列表?
    • 如果您自己处理填充事件,您只需将 ItemsSource 设置为匹配的候选者。
    • 很好的解决方案!
    猜你喜欢
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多