【发布时间】:2009-03-13 12:43:48
【问题描述】:
我想在 WPF 文本框中显示一个选择,即使它不在焦点上。我该怎么做?
【问题讨论】:
我想在 WPF 文本框中显示一个选择,即使它不在焦点上。我该怎么做?
【问题讨论】:
我已将此解决方案用于 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;
}
TextBox 不会意识到它失去了焦点,仍然会显示突出显示的选择。
在这种情况下,我没有使用数据绑定,因此这可能会弄乱双向绑定。您可能必须在 LostFocus 事件处理程序中强制绑定。像这样的:
Binding binding = BindingOperations.GetBinding(this, TextProperty);
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();
}
【讨论】:
另一种选择是在 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>
【讨论】:
TextBoxBase.IsInactiveSelectionHighlightEnabled 属性自 .NET Framework 4.5 起可用
public bool IsInactiveSelectionHighlightEnabled { get; set; }
【讨论】:
SystemColors.InactiveSelectionHighlightBrushKey 的默认颜色是几乎不明显的暗灰色,因此建议将其更改为更鲜艳的颜色。
public class CustomRichTextBox : RichTextBox
{
protected override void OnLostFocus(RoutedEventArgs e)
{
}
}
【讨论】:
我发现列出的建议(添加 LostFocus 处理程序,定义 FocusScope)不起作用,但我确实遇到了此处列出的代码:http://naracea.com/2011/06/26/selection-highlight-and-focus-on-wpf-textbox/,它创建了一个自定义 Adorner,在未聚焦时突出显示文本。
【讨论】: