简体   繁体   中英

Focus control for Custom User Control

I have a UserControl defined such that:

UserControl
  TextBox
  Button (Clear)

I have a GotFocus handler on the UserControl so that whenever it gets focus, it calls 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. I want this to act as either:

  • One GotFocus event
  • One GotFocus event (button), One LostFocus event(button), One GotFocus event (textbox)

I have played with FocusManager.IsFocusScope to no avail. Is there even a way to trigger a manual LostFocus right before I call Textbox.Focus ?

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():

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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