IneedHelp
IneedHelp

Reputation: 1758

Show textbox text highlight while textbox is out of focus

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?

Upvotes: 2

Views: 1960

Answers (4)

Kux
Kux

Reputation: 1489

Here is the completed solution with XAML. The solution keywords are:

  • IsInactiveSelectionHighlightEnabled
  • InactiveSelectionHighlightBrushKey

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 ;-)

Upvotes: 0

Rudey
Rudey

Reputation: 4965

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.

Upvotes: 1

Henk Holterman
Henk Holterman

Reputation: 273621

Set

textBox1.IsInactiveSelectionHighlightEnabled = true;

(Apparently this is new in Fx 4.5)

Upvotes: 4

Derek
Derek

Reputation: 8630

You could Use the code Below on both the On Focus and Leaving Focus event handlers :-

textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

Upvotes: -1

Related Questions