如何更改WPF TextBox的突出显示文本颜色?
-
03-07-2019 - |
题
WPF TextBox
本身使用System Highlight颜色绘制所选文本的背景。我想覆盖它并使其保持一致,因为它因操作系统/用户主题而异。
对于 ListBoxItem
,有一个巧妙的技巧(见下文),你可以覆盖 HighlightBrushKey
在焦点设置中自定义系统突出显示颜色:
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="LightGreen"/>
</Style.Resources>
</Style>
遗憾的是,同样的技巧对 TextBox
不起作用。除了“覆盖 ControlTemplate
”之外,是否还有其他任何想法?
感谢您的任何建议!
解决方案
史蒂夫提到:注意:此行为似乎已添加到WPF 4中。
我碰到了同样的问题。
Dr.WPF说
“这完全不可能 当前的.NET版本(3.0&amp; 3.5 测试版)。该控件是硬编码的 使用系统设置......它没有 完全看一下控制模板。“
http: //social.msdn.microsoft.com/Forums/en-US/wpf/thread/bbffa6e3-2745-4e72-80d0-9cdedeb69f7f/
其他提示
自.NET 4起, <代码> TextBoxBase.SelectionBrush 代码>
例如
<TextBox SelectionBrush="Red" SelectionOpacity="0.5"
Foreground="Blue" CaretBrush="Blue">
这是一个Windows 8.1 .Net 4.6.1测试解决方案,用于自定义应用程序中每个 TextBox
的 SelectionBrush
:
/// 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;
}
如果您想通过 TextBoxBase
包含 RichTextBox
替换类型名称 TextBox
4次。
您可以为TextBox创建样式并为背景编写Setter。 TextBox样式应该是默认样式,以便可视树下的任何TextBox都将获得更改的TextBox
<Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
试试这个:
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="Border" Property="Background" Value="OrangeRed"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
不隶属于 StackOverflow