在GotFocus()时改变Wpf文本框的聚焦边框颜色

时间:2017-02-02 22:57:11

标签: c# wpf vb.net

我想要的:当任何文本框具有焦点时,将边框颜色更改为黄色。

我尝试了什么:

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

没有快乐。无法弄清楚为什么边界仍然是蓝色的。 这与How to change the color of the Border of a TextBox when it has focus?相似,但不重复。

1 个答案:

答案 0 :(得分:16)

您需要修改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>