我正在创建一个带有 ListBox 的应用程序。我希望用户能够点击它,开始输入,并看到他们的文本出现在该项目中。下面是一个几乎有效的简化版本:
using System.Windows.Forms;
namespace ListboxTest
{
public partial class ListboxTest : Form
{
InitializeComponent();
listBox1.Items.Add("");
listBox1.Items.Add("");
listBox1.KeyPress += new KeyPressEventHandler(ListBoxKeyPress);
}
private void ListBoxKeyPress(object sender, KeyPressEventArgs e)
{
ListBox lbx = (ListBox)sender;
if (lbx.SelectedIndices.Count != 1)
return;
int temp = lbx.SelectedIndex;
string value = lbx.Items[temp].ToString();
value += e.KeyChar;
lbx.Items[temp] = value;
}
}
选择 ListBox 后,用户可以开始输入并查看显示的文本。一切都按预期进行,直到发生两件事:
用户从一项切换到另一项(单击进入不同的输入或使用向上/向下箭头),然后按
用户按下与未选择项目名称中的第一个字符对应的键。
从那时起,只要用户按下那个键(在我的例子中是“1”),ListBox 的选定项就会改变。只有两个项目(都以“1”开头)时,按“1”会导致 ListBox 将所选项目从索引 0 切换到索引 1(反之亦然)。
我做了一些实验,这就是我发现的。
如果 ListBox 有两个以上的项目,它将循环遍历所有以前输入的具有相同起始字符的元素。从未选择过的项目将被跳过。
我试过的:
清除选定的索引 ListBox.SetSelected(int index, bool selected)
清除选定的索引 ListBox.ClearSelected()
设置Listbox.SelectionMode
为SelectionMode.One
我使用的是 VS 2015 Professional、Windows 7 SP1 (x64)、C# 6.0 和目标 .NET 4.6.1。
所以,我的问题是:发生了什么,我该如何解决?
相关分类