简体   繁体   English

无法在WPF中将焦点设置在TextBox上

[英]Cannot set focus on TextBox in WPF

I can't set focus on my TextBox , I have this code: 我不能将重点放在TextBox ,我有以下代码:

private void txbUid_KeyDown(object sender, KeyEventArgs e)
{
  if (e.Key != Key.Tab) return; // here control doesn't loose focus

  string stringUid = txbUid.Text;
  long uid;

  if (!TryParseUid(stringUid, out uid))
  {
    //string errMsg = $"Niepoprawny kod UID: {stringUid}";
    //lblError.Text = errMsg;
    //this.LogError(errMsg);
    //txbUid.Text = "";
    //txbUid.Focus();
    return; // here control looses focus
  }
}

As you can see, I tried commenting out particular lines to see whether on of them is causing the problem. 如您所见,我尝试注释掉特定行,以查看其中是否引起了问题。 But nothing has worked. 但是没有任何效果。

All this was caused by pressing tab button. 这一切都是由于按下Tab键引起的。

If it wasn't pressed, control stay focused as it should - and that was misleading. 如果没有按下,则控制权应集中在应有的位置上,这会产生误导。

When I pressed tab, then by default, the next control got focus, ie I handled the event, but it was passed further to containing control, which set focus on other control. 当我按下tab键时,默认情况下, 下一个控件获得了焦点,即我处理了该事件,但是它进一步传递给了包含控件的控件,该控件将焦点设置在其他控件上。 Thus unexpected behaviour. 因此出现了意外行为。

The solution was to set e.Handled , instead of using Focus() method (after which further processing of an event set focus to other control anyway), to true in the event, so pressing tab event wasn't processed any further. 解决方案是将e.Handled设置为e.Handled ,而不是使用Focus()方法(此后对事件的进一步处理将焦点设置为其他控件)设置为true ,因此不再进一步处理tab事件。

Example code: 示例代码:

private void txbUid_KeyDown(object sender, KeyEventArgs e)
{
  if (e.Key != Key.Tab) return; // here control doesn't loose focus

  string stringUid = txbUid.Text;
  long uid;

  if (!TryParseUid(stringUid, out uid))
  {
    // no need to comment out anything
    string errMsg = $"Niepoprawny kod UID: {stringUid}";
    lblError.Text = errMsg;
    this.LogError(errMsg);
    txbUid.Text = "";
    // mark event as handled
    e.Handled = true;
    return;
  }
}

The Tab character will be handled internally by the TextBox . Tab字符将由TextBox在内部处理。 You can try setting e.Handled = true before returning. 您可以尝试在返回之前设置e.Handled = true If that doesn't work, you need to handle PreviewKeyDown instead (and don't forget to set the Handled property). 如果这不起作用,则需要改为处理PreviewKeyDown (并且不要忘记设置Handled属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM