gpt4 book ai didi

c# - 为什么TextBox Border Color在WPF中坚持不变?

转载 作者:太空狗 更新时间:2023-10-29 20:54:39 26 4
gpt4 key购买 nike

据我所知,当文本框获得焦点时,我应该使用样式触发器来更新文本框的边框颜色。但是无论我做什么,它总是变成系统默认的蓝色,而不是我指定的黑色。

有人有什么想法吗?

代码如下:

<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}"

当状态为 FocusMouseOver 时,它们负责蓝色渐变边框,并且可能在 BorderThicknessBorderBrush。如果他们删除/重置,蓝色渐变边框将消失,并且不需要将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com