如何在没有聚焦的情况下保持WPF TextBox选择?

Dmi*_*ruk 21 c# wpf textbox

我希望在WPF TextBox中显示一个选项,即使它不在焦点上.我怎样才能做到这一点?

Joh*_*zek 27

我已经将此解决方案用于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;
  }
Run Code Online (Sandbox Code Playgroud)

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

在这种情况下,我没有使用数据绑定,因此可能会破坏双向绑定.您可能必须在LostFocus事件处理程序中强制绑定.像这样的东西:

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

  • 这通常可以正常工作,但是会中断在其中没有选择的非焦点RichTextBox上的滚动-选择突出显示项不会随文本移动。 (2认同)

Zam*_*oni 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>
Run Code Online (Sandbox Code Playgroud)


Mak*_*man 7

TextBoxBase.IsInactiveSelectionHighlightEnabled属性自 .NET Framework 4.5 起可用

public bool IsInactiveSelectionHighlightEnabled { get; set; }
Run Code Online (Sandbox Code Playgroud)

  • 两个注意事项:(1)当焦点丢失时,将应用非活动突出显示,因此如果该字段从未获得焦点,则它不会出现。当您以编程方式设置选择时很重要。(2) `SystemColors.InactiveSelectionHighlightBrushKey` 的默认颜色是几乎不易察觉的暗灰色,因此建议将其更改为更丰富多彩的颜色。 (5认同)