【发布时间】:2026-02-19 12:45:01
【问题描述】:
我又遇到了一个问题。
我已设置我的组合框,使其仅接受与组合框项目中任何项目的名称匹配的字符。
现在我遇到了一个问题。请看一下我的代码,然后我会向您解释问题:
private void myComboBox_KeyUp(object sender, KeyEventArgs e)
{
// Get the textbox part of the combobox
TextBox textBox = cbEffectOn.Template.FindName("PART_EditableTextBox", cbEffectOn) as TextBox;
// holds the list of combobox items as strings
List<String> items = new List<String>();
// indicates whether the new character added should be removed
bool shouldRemoveLastChar = true;
for (int i = 0; i < cbEffectOn.Items.Count; i++)
{
items.Add(cbEffectOn.Items.GetItemAt(i).ToString());
}
for (int i = 0; i < items.Count; i++)
{
// legal character input
if (textBox.Text != "" && items.ElementAt(i).StartsWith(textBox.Text))
{
shouldRemoveLastChar = false;
break;
}
}
// illegal character input
if (textBox.Text != "" && shouldRemoveLastChar)
{
textBox.Text = textBox.Text.Remove(textBox.Text.Length - 1);
textBox.CaretIndex = textBox.Text.Length;
}
}
在最后一个 if 条件下,我从组合框中删除了最后一个字符。但是用户可以使用方向键或鼠标来改变光标的位置,在文本中间输入文本。
因此,如果通过在文本中间输入一个字符,如果文本变得无效,我的意思是如果它与 ComboBox 中的项目不匹配,那么我应该删除最后输入的字符。谁能建议我如何获取最后插入的字符并将其删除?
更新:
string OldValue = "";
private void myComboBox_KeyDown(object sender, KeyEventArgs e)
{
TextBox textBox = cbEffectOn.Template.FindName("PART_EditableTextBox", cbEffectOn) as TextBox;
List<String> items = new List<String>();
for (int i = 0; i < cbEffectOn.Items.Count; i++)
{
items.Add(cbEffectOn.Items.GetItemAt(i).ToString());
}
OldValue = textBox.Text;
bool shouldReplaceWithOldValue = true;
string NewValue = textBox.Text.Insert(textBox.CaretIndex,e.Key.ToString()).Remove(textBox.CaretIndex + 1,textBox.Text.Length - textBox.CaretIndex);
for (int i = 0; i < items.Count; i++)
{
// legal character input
if (NewValue != "" && items.ElementAt(i).StartsWith(NewValue, StringComparison.InvariantCultureIgnoreCase))
{
shouldReplaceWithOldValue = false;
break;
}
}
//// illegal character input
if (NewValue != "" && shouldReplaceWithOldValue)
{
e.Handled = true;
}
}
这里我已经尝试移动KeyDown事件中的所有代码来解决上述问题。此代码运行良好,但有 1 个问题。
如果我有任何名为 Birds & Animals 的项目,则在输入 Birds 和空格后,我无法输入 &。
我知道问题出在哪里,但不知道解决方案。
问题是:要输入 & 我必须按 shift 键,然后按 7 键。但两者都作为不同的密钥发送。
我想到的解决方案: 1)我应该将我的代码移动到 KeyUp 事件。但是这里会出现长按和快速打字的问题。 2)我想我应该用一些东西替换 e.Key 。但不知道是什么。
【问题讨论】:
-
您是否正在尝试创建 Intellisense ComboBox?
-
我不知道,你说的智能感知组合框是什么意思。我基本上想强制用户输入与 ComboBox 的一项匹配的文本。