不集中时如何保持WPF文本框选择?

How to keep WPF TextBox selection when not focused?(不集中时如何保持WPF文本框选择?)
本文介绍了不集中时如何保持WPF文本框选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 WPF 文本框中显示一个选择,即使它不在焦点上.我该怎么做?

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

推荐答案

我已经将此解决方案用于 RichTextBox,但我认为它也适用于标准文本框.基本上,您需要处理 LostFocus 事件并将其标记为已处理.

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;
  }

TextBox 不会意识到它失去了焦点,仍然会显示突出显示的选择.

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

在这种情况下我没有使用数据绑定,所以这可能会弄乱双向绑定.您可能必须在 LostFocus 事件处理程序中强制绑定.像这样的:

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();
     }

这篇关于不集中时如何保持WPF文本框选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)