0
votes

I'm using AutoCompleteBox from the wpf toolkit and I implement the populating by my own since there is a lot of data and I want to do the search in a background thread.

this is what heppans when I search for the number 12. while it should show me 4 results - 12,120,121,122.

What am I doing wrong ?

Guide on msdn that I tried to folow: http://msdn.microsoft.com/en-us/library/system.windows.controls.autocompletebox.populating(VS.95).aspx

alt text

XAML:

<Grid>
    <Controls:AutoCompleteBox x:Name="txtSearch" Populating="AutoCompleteBox_Populating" Height="30"  Background="Beige" />
</Grid>

Code behind:

 public partial class Window1 : Window {

    private int MAX_NUM_OF_RESULTS = 3;

    public List<Person> Persons { get; set; }
    public List<string> Results { get; set; }

    public Window1() {
        InitializeComponent();

        Persons = new List<Person>();
        for (var i = 0; i < 1000000; i++) {
            Persons.Add(new Person { Name = i.ToString() });
        }

        Results = new List<string>();
    }

    private void AutoCompleteBox_Populating(object sender, PopulatingEventArgs e) {

        e.Cancel = true;

        var b = new BackgroundWorker();
        b.RunWorkerAsync(txtSearch.SearchText);
        b.DoWork += b_DoWork;
        b.RunWorkerCompleted += b_RunWorkerCompleted;
    }

    void b_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
        txtSearch.ItemsSource = Results;
        txtSearch.PopulateComplete();
    }


    void b_DoWork(object sender, DoWorkEventArgs e) {

        Results.Clear();
        var counter = 0;

        foreach (var person in Persons) {
            if (person.Name.StartsWith(e.Argument.ToString())) {
                Results.Add(person.Name);
                counter++;

                if (counter > MAX_NUM_OF_RESULTS) {
                    break;
                }
            }
        }
    }
}

Class Person:

 public class Person {
    public string Name;
}
2

2 Answers

4
votes

Try change the order to the following

var b = new BackgroundWorker();
b.DoWork += b_DoWork;
b.RunWorkerCompleted += b_RunWorkerCompleted;
b.RunWorkerAsync(txtSearch.SearchText);
1
votes

Are you certain your search logic is actually executing? If so, are the expected results in Results prior to assigning them to ItemsSource?

I think this:

    var b = new BackgroundWorker();
    b.RunWorkerAsync(txtSearch.SearchText);
    b.DoWork += b_DoWork;
    b.RunWorkerCompleted += b_RunWorkerCompleted;

Should be this:

    var b = new BackgroundWorker();
    b.DoWork += b_DoWork;
    b.RunWorkerCompleted += b_RunWorkerCompleted;
    b.RunWorkerAsync(txtSearch.SearchText);

Otherwise you risk having the worker start before setting up event handlers.