据我所知,当文本框获得焦点时,我应该使用样式触发器来更新文本框的边框颜色。但是无论我做什么,它总是变成系统默认的蓝色,而不是我指定的黑色。
有人有什么想法吗?
代码如下:
<UserControl.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="BorderBrush" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
最佳答案
尝试设置 BorderThickness
值大于 1
(默认):
<Window.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="BorderBrush" Value="Pink" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<TextBox Width="100"
Height="30"
Text="Test"
BorderThickness="4" />
</Grid>
在 Windows 7 上测试。
编辑:为什么会这样?
我查看了 Windows 7 下 Blend 中 TextBox
的默认样式,这里是 ControlTemplate:
<ControlTemplate x:Key="TextBoxControlTemplate1" TargetType="{x:Type TextBox}">
<Microsoft_Windows_Themes:ListBoxChrome x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderFocused="{TemplateBinding IsKeyboardFocusWithin}" SnapsToDevicePixels="true">
<ScrollViewer x:Name="PART_ContentHost" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Microsoft_Windows_Themes:ListBoxChrome>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
这里有两个参数:
RenderMouseOver="{TemplateBinding IsMouseOver}"
RenderFocused="{TemplateBinding IsKeyboardFocusWithin}"
当状态为 Focus
和 MouseOver
时,它们负责蓝色渐变边框,并且可能在 BorderThickness
和 BorderBrush
。如果他们删除/重置
,蓝色渐变边框将消失,并且不需要将 BorderThickness
的值设置为大于 1。
在 ILSpy
中,我在 TextBoxBase 类中找到了 ChangeVisualState(bool)
方法,它是:
internal override void ChangeVisualState(bool useTransitions)
{
if (!base.IsEnabled)
{
VisualStateManager.GoToState(this, "Disabled", useTransitions);
}
else
{
if (this.IsReadOnly)
{
VisualStateManager.GoToState(this, "ReadOnly", useTransitions);
}
else
{
if (base.IsMouseOver)
{
VisualStateManager.GoToState(this, "MouseOver", useTransitions);
}
else
{
VisualStateManager.GoToState(this, "Normal", useTransitions);
}
}
}
if (base.IsKeyboardFocused)
{
VisualStateManager.GoToState(this, "Focused", useTransitions);
}
else
{
VisualStateManager.GoToState(this, "Unfocused", useTransitions);
}
base.ChangeVisualState(useTransitions);
}
事实证明,这些视觉状态是“系统地”实现的,并且在不存在的样式中。
关于c# - 为什么TextBox Border Color在WPF中坚持不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21798326/