How to keep WPF TextBox selection when not focused

2019-01-11 17:18发布

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

标签: c# wpf textbox
5条回答
神经病院院长
2楼-- · 2019-01-11 17:37

TextBoxBase.IsInactiveSelectionHighlightEnabled Property has available since .NET Framework 4.5

public bool IsInactiveSelectionHighlightEnabled { get; set; }

查看更多
萌系小妹纸
3楼-- · 2019-01-11 17:41

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.

查看更多
SAY GOODBYE
4楼-- · 2019-01-11 17:42

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();
     }
查看更多
兄弟一词,经得起流年.
5楼-- · 2019-01-11 17:46

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>
查看更多
女痞
6楼-- · 2019-01-11 17:50
public class CustomRichTextBox : RichTextBox
{
     protected override void OnLostFocus(RoutedEventArgs e)
     {

     }
}
查看更多
登录 后发表回答