在 GotFocus() 时更改 Wpf 文本框的聚焦边框颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42013899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the focused border color of a Wpf textbox when it GotFocus()
提问by DrDamnit
What I want: to change the border color to yellow when any textbox has focus.
我想要什么:当任何文本框具有焦点时将边框颜色更改为黄色。
What I tried:
我试过的:
<Window.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="BorderBrush" Value="Yellow"></Setter>
<Setter Property="BorderThickness" Value="1"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
No joy. Cannot figure out why the border remains blue. This is similar, but not a duplicate of How to change the color of the Border of a TextBox when it has focus?.
没有喜悦。无法弄清楚为什么边界保持蓝色。这与如何更改具有焦点时文本框的边框的颜色类似,但不是重复的?.
回答by mm8
You need to modify the control template of the TextBox. Adding a trigger to the style is not enough. This should work:
您需要修改TextBox 的控件模板。向样式添加触发器是不够的。这应该有效:
<Style TargetType="TextBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
<ScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="#FF7EB4EA"/>
</Trigger>
<Trigger Property="IsFocused" Value="true">
<Setter Property="BorderBrush" TargetName="border" Value="Yellow"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
You can find the original style template in the WPF source code: https://github.com/dotnet/wpf/blob/c271205b80c27df976acbd7236ec637090d127c1/src/Microsoft.DotNet.Wpf/src/Themes/XAML/TextBox.xaml#L415-L441
您可以在 WPF 源代码中找到原始样式模板:https: //github.com/dotnet/wpf/blob/c271205b80c27df976acbd7236ec637090d127c1/src/Microsoft.DotNet.Wpf/src/Themes/XAML/TextBox.xaml-L#4L411

