如何在WPF TextBox失去焦点时保留选择内容?

26

我想即使WPF文本框失去焦点也能显示其选定内容。我该如何实现?

5个回答

29

我已经使用这个解决方案来处理RichTextBox,但我认为它也适用于标准文本框。基本上,你需要处理LostFocus事件并将其标记为已处理。

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

文本框将不会意识到它失去了焦点,并且仍然会显示突出显示的选择。

在这种情况下,我没有使用数据绑定,因此这可能会破坏双向绑定。您可能需要在LostFocus事件处理程序中强制绑定。可以像这样实现:

     Binding binding = BindingOperations.GetBinding(this, TextProperty);
     if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
         binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
     {
        BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();
     }

+1 不错的解决方案 - 帮助我创建了一个搜索功能... 谢谢 - reSPAWNed
2
这基本上是有效的,但会破坏非聚焦RichTextBox中带有选择的滚动 - 选择高亮不随文本移动。 - Cameron
更好的答案在下面。 - Casey Anderson
如果您从未进入文本框,则此方法将无法正常工作。如果在呈现文本框之前设置了选择,或者在程序的其他地方更改了选择,那么当文本框处于非活动状态时,您需要做什么才能显示选择内容? - DanW
在多行文本框中,这种方法不起作用,它无法随着文本滚动选择。 - henon

12

5
两个注释:(1)当焦点丢失时应用非活动高亮显示,因此如果字段从未获得焦点,它将不会出现。在以编程方式设置选择时非常重要。 (2)SystemColors.InactiveSelectionHighlightBrushKey的默认颜色是几乎不可见的暗灰色,因此建议将其更改为更丰富多彩的颜色。 - fadden
在 .NET 4 中,你可以使用文本框的 SelectionBrush 属性。当你将其设置为例如 Brushes.Yellow 时,你会得到一个仍然很明显的非活动选择。 - henon

10

另一个选择是在XAML中定义一个单独的焦点范围,以保持第一个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>

1
这个网址http://wpfhacks.blogspot.com/2009/06/correct-way-keep-selection-in-textbox.html有一个很好的视觉演示。 - mtlynch
这个解决方案更符合我的便利性。 - tharibo

1
public class CustomRichTextBox : RichTextBox
{
     protected override void OnLostFocus(RoutedEventArgs e)
     {

     }
}

1

链接已经失效,现在可以在 https://jiribrossmann.com/projects/naracea/2011/06/26/selection-highlight-and-focus-on-wpf-textbox/ 找到它。 - Zev Spitz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接