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

后端 未结 5 829
醉梦人生
醉梦人生 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:34

    Since .NET 4, TextBoxBase.SelectionBrush

    eg

    <TextBox SelectionBrush="Red" SelectionOpacity="0.5"
             Foreground="Blue" CaretBrush="Blue">  
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-01 23:36

    Try this:

         <Trigger Property="IsHighlighted" Value="True">
                                <Setter TargetName="Border" Property="Background" Value="OrangeRed"/>
                                <Setter Property="Foreground" Value="White"/>
                            </Trigger>
    
    0 讨论(0)
  • 2021-01-01 23:52

    As Steve mentioned : NOTE: This behavior appears to be added to WPF 4.

    I bumped into the same problem.

    As Dr.WPF says

    "It is entirely impossible in the current .NET releases (3.0 & 3.5 beta). The control is hardcoded to use the system setting... it doesn't look at the control template at all."

    http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bbffa6e3-2745-4e72-80d0-9cdedeb69f7f/

    0 讨论(0)
  • 2021-01-02 00:02

    You can create a Style for the TextBox and write a Setter for the background. The TextBox style should be a default one so that any TextBox which comes under the visual tree will get the changed TextBox

    <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
    
    0 讨论(0)
提交回复
热议问题