Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep WPF TextBox selection when not focused?

Tags:

I want to show a selection in a WPF TextBox even when it's not in focus. How can I do this?

like image 499
Dmitri Nesteruk Avatar asked Mar 13 '09 12:03

Dmitri Nesteruk


1 Answers

I have used this solution for a RichTextBox, but I assume it will also work for a standard text box. Basically, you need to handle the LostFocus event and mark it as handled.

  protected void MyTextBox_LostFocus(object sender, RoutedEventArgs e)   {          // When the RichTextBox loses focus the user can no longer see the selection.      // This is a hack to make the RichTextBox think it did not lose focus.      e.Handled = true;   } 

The TextBox will not realize it lost the focus and will still show the highlighted selection.

I'm not using data binding in this case, so it may be possible that this will mess up the two way binding. You may have to force binding in your LostFocus event handler. Something like this:

     Binding binding = BindingOperations.GetBinding(this, TextProperty);      if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||          binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)      {         BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();      } 
like image 60
John Myczek Avatar answered Sep 17 '22 18:09

John Myczek