我已经搜索了一个答案,虽然在使用带有字符串类型项目的列表框时有一个可以工作,但我无法弄清楚当我的项目是类型时如何转换
KeyValuePair<string, ChangeRec>
我希望能够在我在列表框中键入时进行搜索(不能使用 ComboBox,因为控件需要在表单上具有特定大小),通过键(文本)项进行搜索。感谢@Marcel Popescu 的起点。这是我的代码版本(仅在失败的行上方进行了注释,因为它不能正确地将 kvp 项转换为字符串):
private string searchString;
private DateTime lastKeyPressTime;
private void lbElementNames_KeyPress(object sender, KeyPressEventArgs e)
{
this.IncrementalSearch(e.KeyChar);
e.Handled = true;
}
private void IncrementalSearch(char ch)
{
if ((DateTime.Now - this.lastKeyPressTime) > new TimeSpan(0, 0, 1))
{
this.searchString = ch.ToString();
}
else
{
this.searchString += ch;
}
this.lastKeyPressTime = DateTime.Now;
//* code falls over HERE *//
var item =
this.lbElementNames.Items.Cast<string>()
.FirstOrDefault(it => it.StartsWith(this.searchString, true, CultureInfo.InvariantCulture));
if (item == null) return;
var index = this.lbElementNames.Items.IndexOf(item);
if (index < 0) return;
this.lbElementNames.SelectedIndex = index;
}