问题描述
我想在 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文本框选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!