ComboBox KeyDown事件如何考虑最后按下的键

ComboBox KeyDown event how to take into account last pressed key

我有一个可编辑的组合框,必须处理输入的值(必须是数字)。 在 keydown 事件中,我分析 combobox.text 并采取相应行动。 当然,在这种情况下 combobox.text 应包含按键事件之前的所有文本。相反,我希望包含最终的完整文本键。

我试过

e.handled=true;

在分析 combobox.text 之前,但这没有用。

作为辅助解决方案,我分析了 e.key 并且必须将其转换为字符串并加以处理。问题是它是一个keyeventargs。 试过了

char ch ;
String str;
if (e.Key > Key.D0 && e.Key < Key.D9)
{
  ch = (char)((int)e.Key - (int)Key.D0);
  str = ch.ToString();
}

但是没用

---添加--- 对不起,我没有说清楚,我会尽力让它变得更好。 我想在以下事件中处理我的组合框

private void ComboBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)

在里面我想做一些类似

的事情
Analyze(combobox.text)

简而言之

private void ComboBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
{
 if((e.Key > Key.D0 && e.Key < Key.D9) || (e.Key > Key.NumPad0 && e.Key < Key.NumPad9))
  {
    Analyze(comboBox.text)---->text here has to be the combobox.text plus the new pressed key 
  }
}

我不完全清楚 "act accordingly" 对你的情况意味着什么,但试试这个作为你的辅助解决方案:

        string str = string.Empty;
        if (e.Key > Key.D0 && e.Key < Key.D9)
        {
            str = ((int)e.Key - (int)Key.D0).ToString();
        }
        MessageBox.Show(str);

将其放入 ComboBox 的 keydown 事件 returns 对我来说是正确的字符串,假设正确意味着获取用户刚刚按下的数字键的字符串表示形式。

我很好奇你的最终目标是什么。也许对此进行详细说明会得到更好的答案。您是否必须在输入的每个键上验证输入?为什么?

我不能完全理解你想要什么,但我会尽力而为。如果要读取用户发短信的字符,使用事件 PreviewTextInput:

更方便

XAML:

<ComboBox Name="comboBox" IsEditable="True" PreviewTextInput="comboBox_PreviewTextInput"/>

C#:

string theWholeString;
private void comboBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
   string currentCharacter = e.Text;
   theWholeString += e.Text;
}

更好,因为您不必弄清楚输入的是数字还是字符串。

如果我误解了你,请告诉我。

除了 Rowbear 提出的解决方案之外,还有一种更简单的方法可以解决我的问题。那就是使用 ComboBox_KeyUp 事件。通过这样做,新密钥已经被确认。我说我想把钥匙放下来误导了所有人,这是我的错。为了完整起见,我添加了这个