我想在绑定(bind)到列表框的键值对列表上实现增量搜索。
如果我有三个值(AAB、AAC、AAD),那么用户应该能够在可用列表框中选择一个项目并键入 AAC,并且该项目应该突出显示并处于焦点状态。它也应该以增量方式进行。
处理此问题的最佳方法是什么?
最佳答案
向 KeyChar 事件添加一个处理程序(在我的例子中,列表框被命名为 lbxFieldNames):
private void lbxFieldNames_KeyPress(object sender, KeyPressEventArgs e)
{
IncrementalSearch(e.KeyChar);
e.Handled = true;
}
(重要:您需要 e.Handled = true;
因为列表框默认执行“转到以该字符开头的第一个项目”搜索;我花了一段时间才弄清楚为什么我的代码不工作。)
IncrementalSearch 方法是:
private void IncrementalSearch(char ch)
{
if (DateTime.Now - lastKeyPressTime > new TimeSpan(0, 0, 1))
searchString = ch.ToString();
else
searchString += ch;
lastKeyPressTime = DateTime.Now;
var item = lbxFieldNames
.Items
.Cast<string>()
.Where(it => it.StartsWith(searchString, true, CultureInfo.InvariantCulture))
.FirstOrDefault();
if (item == null)
return;
var index = lbxFieldNames.Items.IndexOf(item);
if (index < 0)
return;
lbxFieldNames.SelectedIndex = index;
}
我实现的超时是一秒,但是你可以通过修改if
语句中的TimeSpan
来改变它。
最后,你需要声明
private string searchString;
private DateTime lastKeyPressTime;
关于c# - 如何在列表框上实现增量搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7556318/