I have a textbox with some text in it. How do I prevent the textbox from hiding the selected text highlight when the textbox loses focus?
Set
textBox1.IsInactiveSelectionHighlightEnabled = true;
(Apparently this is new in Fx 4.5)
You could extend from the TextBox class, and play around with the SelectionChanged event.
Most of the time, changing default behaviour of controls is a bad idea. The user could experience it as unexpected behaviour, which is bad. In your case, if you manage to create such textbox, the user could select text in multiple textboxes at te same time, since the selection doesn't hide.
Tell me, what is the reason why you want the selected text to remain highlighted? 'Cause maybe there is another way.
EDIT : Apparantly such feature is supported in .NET 4.5: IsInactiveSelectionHighlightEnabled
.
Here is the completed solution with XAML. The solution keywords are:
With IsInactiveSelectionHighlightEnabled
you can enable the feature
end with InactiveSelectionHighlightBrush
you can override the default brush which is 'Transparent'
<Style x:Key="TextBox.AlwaysShowSelection" TargetType="TextBox">
<Style.Resources>
<SolidColorBrush
x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
Color="{StaticResource {x:Static SystemColors.HighlightColorKey}}"/>
</Style.Resources>
<Setter Property="IsInactiveSelectionHighlightEnabled" Value="True"/>
</Style>
And yes you can also override the InactiveSelectionHighlightBrush in global scope, but I wanted to show it only for a specific textbox style.
Because we have meanwhile 2022. I use .NET 6.0 but this should work also in older frameworks (but not too old like .NET 4.0 ;-)
You could Use the code Below on both the On Focus and Leaving Focus event handlers :-
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.