我想在WPF文本框中展示选定内容,即使它没有获得焦点。我该怎么做?
如何在失去焦点时保持WPF TextBox的选择?
原标题:
最佳回答
我已经用这个解决方法来处理一个RichTextBox,但我认为它同样适用于标准文本框。基本上,你需要处理失去焦点事件并标记它为已处理。
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();
}
问题回答
另一种选择是在XAML中定义一个单独的焦点范围以保持第一个文本框的选择。
<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>
自.NET Framework 4.5以来,TextBoxBase.IsInactiveSelectionHighlightEnabled属性可用。
public bool IsInactiveSelectionHighlightEnabled { get; set; }
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/,它创建了一个自定义的装饰器,当没有焦点时突出显示文本。
相关问题
热门标签
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding