UWP - 在文本框失焦时显示文本框文本突出显示

时间:2016-05-30 11:25:14

标签: c# textbox focus uwp

如果文本框失去焦点,如何防止文本框隐藏所选文本高亮显示?以下行适用于WPF

textBox1.IsInactiveSelectionHighlightEnabled = true;

但是UWP的等价物是什么?

2 个答案:

答案 0 :(得分:0)

据我所知,UWP中没有相应的内容。可能的解决方案之一可能是使用一些图像来突出选择。以下是示例代码:

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

焦点: enter image description here

不在焦点: enter image description here

P.S。我正在更新SelectionChanged事件的背景,但实际上您可以在该事件上创建图像并仅在LostFocus事件上更新。它应该更有效率。

答案 1 :(得分:0)

您可以在Xaml中或通过代码设置SelectionHighlightColorWhenNotFocused属性。您可以将其设置为所需的任何颜色,我只是使用绑定来确保它与SelectionHighlightColor相同,以便于使用。

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