How to avoid losing focus of a TextBox when a button is clicked in wpf?

enter image description here

Now the cursor focuses in the TextBox. If I click on the (RemoveLostFocus) button, the TextBox Lost Focus Event event will fire. But what I need is this Lost Focus event from the TextBox should not fire. is there any way to do this?

private void Window_Loaded(object sender, RoutedEventArgs e) { txtUserName.Focus(); } private void UserName_LostFocus(object sender, RoutedEventArgs e) { if (txtUserName.Text.Length < 1) { MessageBox.Show("UserName should not be empty"); } } private void btnCancel_Click(object sender, RoutedEventArgs e) { this.Close(); anotherWindow.Show(); } 
+4
source share
4 answers

You want to use the attached FocusManager properties to apply focus to the TextBox when Button focus changes

Example:

 <StackPanel> <TextBox Name="txtbx" /> <Button Content="Click Me!" FocusManager.FocusedElement="{Binding ElementName=txtbx}"/> </StackPanel> 

With this solution, The TextBox will always focus, even if you click Button , and the TextBox LostFocus event will not be fired

+6
source

you can set Focusable = "False" to the button. here is the response link enter the link here

0
source

Set Focusable Property

 <Button Focusable="False" /> 
-1
source

In the Click-Event of your button, you can do something like

 this.textBox.Focus(); 

If your lostfocus method looks like this:

 private void UserName_LostFocus(object sender, RoutedEventArgs e){ ... } 

you can prevent lost focus with the following code:

 this.textBox.LostFocus -= UserName_LostFocus; 
-1
source

All Articles