我有样式文本框,它使用控制模板根据视觉状态(鼠标悬停、禁用等)设置背景颜色。代码取自 MS 的 TextBox Templates页。
我想要做的也是根据视觉状态更改前景(字体)颜色。例如,在鼠标悬停时,我想让文本颜色突出,而在禁用时,我想让它变灰
我的 xaml(我已经删除了“正常”和“禁用”的 VisualState 标记以及 Border 的几个 <Color x:Key="EditableControlHiLightColor">Ivory</Color>
<Color x:Key="EditableControlHiLightTextColor">Pink</Color>
<Style TargetType="{x:Type TextBox}">
<Setter Property="MinWidth" Value="100" />
<Setter Property="MinHeight" Value="20" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBoxBase}">
<Border Name="Border"
CornerRadius="4"
Padding="2"
BorderThickness="1">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver" >
<Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="(TextBox.Background).Color">
<EasingColorKeyFrame KeyTime="0" Value="{StaticResource EditableControlHiLightColor}" />
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ScrollViewer Margin="0" x:Name="PART_ContentHost" />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
我首先尝试在 Storyboard 标签内添加一个新的 <Storyboard>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="(TextBox.Background).Color">
<EasingColorKeyFrame KeyTime="0" Value="{StaticResource EditableControlHiLightColor}" />
</ColorAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="(TextBox.Foreground).Color">
<EasingColorKeyFrame KeyTime="0" Value="{StaticResource EditableControlHiLightTextColor}" />
</ColorAnimationUsingKeyFrames>
</Storyboard>
但这没有效果 - 文本颜色保持不变。
我认为这是由于
我已经查看了 SO,似乎与 properties that are set by template binding that cannot be changed 有关。 ,但在我的情况下,我正在尝试进行更改的模板内。
那么,如何使用视觉状态更改控件模板中文本框的前景(字体)颜色?
最佳答案
看来我们只能通过改变TextBox Foreground来改变ScrollViewer Foreground。为此,您可以使用触发器:
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="False">
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{StaticResource ControlDisabledForeground}"/>
</Setter.Value>
</Setter>
</Trigger>
<Trigger Property="IsReadOnly" Value="True">
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="{StaticResource ControlReadOnlyForeground}"/>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
你可以在这里看到完整的代码:
https://gist.github.com/Javad-Amiry2/5897049
关于wpf - 在 ControlTemplate 中更改 WPF TextBox 前景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14869568/