我想即使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;
}
文本框将不会意识到它失去了焦点,并且仍然会显示突出显示的选择。
在这种情况下,我没有使用数据绑定,因此这可能会破坏双向绑定。您可能需要在LostFocus事件处理程序中强制绑定。可以像这样实现:
Binding binding = BindingOperations.GetBinding(this, TextProperty);
if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
{
BindingOperations.GetBindingExpression(this, TextProperty).UpdateSource();
}
TextBoxBase.IsInactiveSelectionHighlightEnabled 属性自 .NET Framework 4.5 版本后可用。
public bool IsInactiveSelectionHighlightEnabled { get; set; }
SystemColors.InactiveSelectionHighlightBrushKey
的默认颜色是几乎不可见的暗灰色,因此建议将其更改为更丰富多彩的颜色。 - fadden另一个选择是在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>
public class CustomRichTextBox : RichTextBox
{
protected override void OnLostFocus(RoutedEventArgs e)
{
}
}