我有一个项目,需要在用户继续删除时,如果当前字段为空,则聚焦于前一个字段。类似于在某处输入CD密钥的情况。您会有几个带有4-5个符号的块。如果您删除第三个文本框,例如,那么第三个文本框被清空后,您将被迫返回到第二个文本框。
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
这段代码本来可以正常运行,但是考虑到我还有另一个onfocus事件,所以textBox2一旦获得焦点就会变为空,由于上面的代码强制让焦点回到textBox1,因此它陷入了循环。
如果我理解正确,我需要捕捉按下Delete键,对吗?但问题在于我不知道如何插入这段代码。
private void Window_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
}
}
在这个函数内部:
private void textBox2_TextChanged(object sender, TextChangedEventArgs e)
{
if (textBox2.Text.Length == 2)
{
Keyboard.Focus(textBox3);
}
// HERE I NEED SOMETHING LIKE ELSE IF (e.Key == Key.Delete) {...
}
请帮我,谢谢。 更新:我尝试了另一种解决方案,但它没有起作用:
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (textBox2.Text.Length == 0)
{
Keyboard.Focus(textBox1);
}
}
}