我正在使用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.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。
所以,我的问题:发生了什么以及我该如何解决?
答案 0 :(得分:2)
如果在Listbox
处于焦点时键入任何键盘键,它实际遍历其所有项目并选择以键入键开头的那些项目(逐个)。所以它是Listbox
的基本行为。
您需要在此处使用KeyEventArgs.SuppressKeyPress属性,因为您需要在KeyEvenArgs
获取KeyDown
的情况下编写逻辑,例如 private void lstBoxItems_KeyDown(object sender, KeyEventArgs e)
{
ListBox lbx = (ListBox)sender;
if (lbx.SelectedIndices.Count != 1)
return;
e.SuppressKeyPress = true;
//calling this method to get char from key data
char keyChar = GetChar(e);
int temp = lbx.SelectedIndex;
string value = lbx.Items[temp].ToString();
value += keyChar;
lbx.Items[temp] = value;
}
尝试以下代码
char GetChar(KeyEventArgs e)
{
int keyValue = e.KeyValue;
if (!e.Shift && keyValue >= (int)Keys.A && keyValue <= (int)Keys.Z)
return (char)(keyValue + 32);
return (char)keyValue;
}
并添加此方法
Filename Filesize Filepath
--------- --------- ---------
test1.exe 5kb /home/program/
test2.exe 6kb /home/program/
test3.mp3 10mb /home/music/
test4.avi 15mb /home/video/
4 files are removed
我搜索了一些其他问题,你可以参考,
How to disable listbox auto select item when pressing key
我有从这里将密钥数据转换为char的方法。
答案 1 :(得分:0)
感谢Amit指出我正确的方向。这是ListBox的默认行为。但是,使用事件处理程序实际上是一种更容易抑制此行为的方法。
使用事件处理程序&#34; KeyPress&#34;时,您可以设置
e.Handled = true
到suppress further processing。这可以防止列表框在键入时选择其他项目。