我正在使用wpf工具包中的AutoCompleteBox,我实现了自己的填充 因为有很多数据,我想在后台线程中进行搜索。
当我搜索12号时,这就是heppans。 虽然它应该显示我4个结果 - 12,120,121,122。
我做错了什么?
我尝试过的msdn指南:http://msdn.microsoft.com/en-us/library/system.windows.controls.autocompletebox.populating(VS.95).aspx
XAML:
<Grid>
<Controls:AutoCompleteBox x:Name="txtSearch" Populating="AutoCompleteBox_Populating" Height="30" Background="Beige" />
</Grid>
代码背后:
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;
}
}
}
}
}
班主任:
public class Person {
public string Name;
}
答案 0 :(得分:4)
尝试将订单更改为以下
var b = new BackgroundWorker();
b.DoWork += b_DoWork;
b.RunWorkerCompleted += b_RunWorkerCompleted;
b.RunWorkerAsync(txtSearch.SearchText);
答案 1 :(得分:1)
您确定您的搜索逻辑实际上正在执行吗?如果是,那么在将结果分配给ItemsSource之前,结果中的预期结果是什么?
我想这个:
var b = new BackgroundWorker();
b.RunWorkerAsync(txtSearch.SearchText);
b.DoWork += b_DoWork;
b.RunWorkerCompleted += b_RunWorkerCompleted;
应该是这样的:
var b = new BackgroundWorker();
b.DoWork += b_DoWork;
b.RunWorkerCompleted += b_RunWorkerCompleted;
b.RunWorkerAsync(txtSearch.SearchText);
否则,您可能会在设置事件处理程序之前让工作人员启动。