简体   繁体   English

自定义用户控件的焦点控件

[英]Focus control for Custom User Control

I have a UserControl defined such that: 我有一个这样定义的UserControl:

UserControl
  TextBox
  Button (Clear)

I have a GotFocus handler on the UserControl so that whenever it gets focus, it calls TextBox.Focus() . 我在UserControl上有一个GotFocus处理程序,因此只要它获得焦点,它就会调用TextBox.Focus() The problem I am running into is that If I click the clear button, it clears the text and then refocuses to the textbox, triggering two GotFocus events on my control. 我遇到的问题是,如果单击“清除”按钮,它将清除文本,然后重新聚焦到文本框,从而触发控件上的两个GotFocus事件。 I want this to act as either: 我希望这可以充当:

  • One GotFocus event 一场GotFocus活动
  • One GotFocus event (button), One LostFocus event(button), One GotFocus event (textbox) 一个GotFocus事件(按钮),一个LostFocus事件(按钮),一个GotFocus事件(文本框)

I have played with FocusManager.IsFocusScope to no avail. 我玩过FocusManager.IsFocusScope无济于事。 Is there even a way to trigger a manual LostFocus right before I call Textbox.Focus ? 在我致电Textbox.Focus之前,是否还有办法触发手动LostFocus吗?

In your GotFocus event you can check whether the mouse is over the clear button and whether the left mouse button is pressed, in such a case you can ignore the call to TextBox.Focus(): 在您的GotFocus事件中,您可以检查鼠标是否在清除按钮上以及是否按下了鼠标左键,在这种情况下,您可以忽略对TextBox.Focus():的调用TextBox.Focus():

private void UserControl_GotFocus(object sender, RoutedEventArgs e)
{
     if ((this.clearButton.IsMouseOver && Mouse.LeftButton == MouseButtonState.Pressed) == false)
     {
         this.textBox.Focus();
     }
}

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

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