文本框始终聚焦

本文关键字:聚焦 文本 | 更新日期: 2023-09-27 18:13:03

我有一个带有文本框和按钮的窗口。我想始终聚焦我的文本框,但允许用户点击按钮。我该怎么做呢?

我尝试过使用一个LostFocusEvent,这将检查谁有焦点,如果它不是按钮,它会聚焦文本框回来,但我总是得到一个System.StackOverflowException…

这是我使用的:

    private void TextLostFocus(object sender, RoutedEventArgs e)
    {
      IInputElement focusedControl = FocusManager.GetFocusedElement(this);
      if (focusedControl != btn && focusedControl != txt)
      {
        txt.Focus();
      }
    }

有办法做到这一点吗?

文本框始终聚焦

在按钮单击事件中,您可以像这样将焦点放回文本框。

textbox.focus();
Textbox.Select();

Focus是用于自定义控件的低级方法。我会坚持使用select()或activate()

private void TextLostFocus(object sender, RoutedEventArgs e)
{
  ((TextBox) sender).Focus();
}

你可以使用ActiveControl属性来设置文本框的焦点。

    this.ActiveControl = yourTextboxName;