tags:

views:

807

answers:

3

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

+4  A: 

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();
     }
John Myczek
This worked! Thanks!
Dmitri Nesteruk
A: 

Works great for TextBox and RichTextBox. Thanks!

Matthias
+2  A: 

Another option is to define a separate focus scope in XAML to maintain the selection in the first TextBox.

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition/>
    <RowDefinition/>
  </Grid.RowDefinitions>

  <TextBox Grid.Row="0" Text="Text that does not loose selection."/>
  <StackPanel Grid.Row="1" FocusManager.IsFocusScope="True">
    <TextBox Text="Some more text here." />
    <Button  Content="Run" />
    <Button Content="Review" />
  </StackPanel>
</Grid>
Zamboni