如何更改WPF文本框的突出显示文本颜色?

如何更改WPF文本框的突出显示文本颜色?,wpf,resources,textbox,styles,highlighting,Wpf,Resources,Textbox,Styles,Highlighting,WPFTextBox本机使用系统高亮颜色绘制选定文本的背景。我想覆盖它并使其一致,因为它因操作系统/用户主题而异 对于ListBoxItems,有一个(见下文)可以覆盖HighlightBrushKey的资源键,以自定义聚焦设置中的系统高亮显示颜色: <Style TargetType="ListBoxItem"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors

WPF
TextBox
本机使用系统高亮颜色绘制选定文本的背景。我想覆盖它并使其一致,因为它因操作系统/用户主题而异

对于
ListBoxItem
s,有一个(见下文)可以覆盖
HighlightBrushKey
的资源键,以自定义聚焦设置中的系统高亮显示颜色:

  <Style TargetType="ListBoxItem">
    <Style.Resources>
      <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGreen"/>
    </Style.Resources>
  </Style>

不幸的是,同样的技巧对
文本框不起作用。除了“覆盖
ControlTemplate
”之外,还有其他想法吗

谢谢你的建议


您可以为文本框创建样式,并为背景编写Setter。TextBox样式应该是默认样式,这样任何位于可视树下的TextBox都将获得更改后的TextBox

<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">

正如Steve提到的:

我碰到了同样的问题

正如WPF博士所说

他说:"这是完全不可能的 当前.NET版本(3.0和3.5 beta)。控件硬编码为 使用系统设置…它不会 请看一下控制模板。”

自.NET 4以来

通过设置SelectionBrush和SelectionCapacity属性,可以指定高亮显示选定文本的笔刷。SelectionCapacity属性指定SelectionBrush的不透明度

例如


试试这个:

     <Trigger Property="IsHighlighted" Value="True">
                            <Setter TargetName="Border" Property="Background" Value="OrangeRed"/>
                            <Setter Property="Foreground" Value="White"/>
                        </Trigger>

这是一个经过Windows 8.1.Net 4.6.1测试的解决方案,用于自定义应用程序中每个
文本框的
选择笔刷

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

如果您想将
RichTextBox
替换为
TextBoxBase

以改变整个文本框的背景色,那么我想知道的是如何只改变突出显示部分的背景。不过还是要谢谢你。谢谢你指出这一点,特别是ControlTemplate也被忽略了,因为我可能会尝试其他方法失败。答案中的第一个链接已失效——“404 |未找到页面”。IsHighlighted不是TextBox上的属性,你会在哪个元素上使用该触发器?我再次查看并确认,这不是TextBox上的属性。我怀疑您使用的是其他类型的控件,或者TextBox的自定义派生版本。上面的示例是针对列表框的。好的,这个问题是关于TextBox的。ListBox是一个已经有了解决方法的示例。
/// 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;
}