How to keep WPF TextBox selection when not focused?

后端 未结 5 653
清酒与你
清酒与你 2020-12-03 07:23

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

相关标签:
5条回答
  • 2020-12-03 07:48

    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>
    
    0 讨论(0)
  • 2020-12-03 07:49
    public class CustomRichTextBox : RichTextBox
    {
         protected override void OnLostFocus(RoutedEventArgs e)
         {
    
         }
    }
    
    0 讨论(0)
  • 2020-12-03 07:56

    I found that the suggestions listed (add a LostFocus handler, defining a FocusScope) to not work, but I did come across the code listed here: http://naracea.com/2011/06/26/selection-highlight-and-focus-on-wpf-textbox/, which creates a custom Adorner that highlights the text when not focused.

    0 讨论(0)
  • 2020-12-03 07:58

    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();
         }
    
    0 讨论(0)
  • TextBoxBase.IsInactiveSelectionHighlightEnabled Property has available since .NET Framework 4.5

    public bool IsInactiveSelectionHighlightEnabled { get; set; }
    
    0 讨论(0)
提交回复
热议问题