How can you change the highlighted text color for a WPF TextBox?

后端 未结 5 858
醉梦人生
醉梦人生 2021-01-01 23:22

The WPF TextBox natively makes use of the System Highlight color for painting the background of selected text. I would like to override this and make it consis

5条回答
  •  情歌与酒
    2021-01-01 23:35

    This is a Windows 8.1 .Net 4.6.1 tested solution to customize the SelectionBrush of each TextBox in the app:

    /// Constructor in App.xaml.cs
    public App() : base()
    {
        // Register an additional SelectionChanged handler for appwide each TextBox
        EventManager.RegisterClassHandler(typeof(TextBox), TextBox.SelectionChangedEvent, RoutedEventHandler(_textBox_selectionChanged));
    }
    
    private void _textBox_selectionChanged(object sender, RoutedEventArgs e)
    {
        // Customize background color of selected text
        (sender as TextBox).SelectionBrush = Brushes.MediumOrchid;
    
        // Customize opacity of background color
        (sender as TextBox).SelectionOpacity = 0.5;
    }
    

    If you want to include RichTextBox replace type name TextBox 4 times by TextBoxBase.

提交回复
热议问题