UWP - Show textbox text highlight while textbox is

2019-07-14 21:09发布

问题:

How do I prevent the textbox from hiding the selected text highlight when the textbox loses focus? The following line worked for WPF

textBox1.IsInactiveSelectionHighlightEnabled = true;

but what is the equivalent for UWP?

回答1:

As I know there is no equivalent in UWP for that. One of possible work-around solutions could be to use some image to keep selection highlighted. Here is sample code:

XAML:

<Border BorderThickness="2" BorderBrush="{ThemeResource TextBoxBorderThemeBrush}" Height="164" Width="684">
    <TextBox x:Name="textBox" TextWrapping="Wrap" Text="TextBox" BorderThickness="0,0,0,0"/>
</Border>

C#:

    private async void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
    {
        // clear background            
        textBox.Background = new SolidColorBrush(Windows.UI.Color.FromArgb(255, 255, 255, 255)); ;

        // render image
        RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
        await renderTargetBitmap.RenderAsync(textBox);

        // set background
        textBox.Background = new ImageBrush()
        {
            ImageSource = renderTargetBitmap
        };
    }

In focus:

Not in focus:

p.s. I'm updating background on SelectionChanged event, but actually you can create image on that event and update only on LostFocus event. It should be more efficient.



回答2:

You can set the SelectionHighlightColorWhenNotFocused property either in Xaml or via code. You can set it to any color you want, I just used binding to make sure it's the same color as the SelectionHighlightColor to make it easy.

<TextBox Style="{StaticResource TextBoxLightStyle}" Name="TextBoxMain" 
     AcceptsReturn="True"
     SelectionHighlightColorWhenNotFocused="{Binding SelectionHighlightColor, ElementName=TextBoxMain, Mode=OneWay}">
</TextBox>