您无需使用ContentControl,只需使用VisualStateManager,即可完成您所寻找的工作
我当然可以通过编辑样式来更改文本颜色,但这没什么用,因为它在我感兴趣的编辑状态中。
例如,将新的Foreground 颜色应用于Button 的文本的状态是MouseOver,
- 首先,在编辑
Button 模板时,Blend 不会为 Button.MouseOver.Foreground 创建 Brush 资源。
所以让我们创建一个。 (只需添加以下行以及其他画笔资源)
<SolidColorBrush x:Key="Button.MouseOver.Foreground" Color="Tomato" />
- 现在我们可以将
Storyboard 应用于contentPresenter 的TextElement.Foreground。
所以您的 VSM 将如下所示:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="contentPresenter"
Storyboard.TargetProperty="(TextElement.Foreground)">
<DiscreteObjectKeyFrame KeyTime="0">
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="{Binding Source={StaticResource Button.MouseOver.Foreground}, Path=Color}" />
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
就是这样。
请注意我们在这里所做的事情只有当Button 的Content 只是文本时,但由于这就是您在问题中提到的用法,您应该没问题。
旁注:
您只需将ContentPresenter 中的TextBlock 切换为ControlTemplate 中的TextBlock,即可完成完全相同的操作。
如果您需要Foreground 可用于Button 中的任何Content,那么您只需将ContentPresenter 切换为ContentControl,您仍然可以以非常相似的方式使用您的VSM Storyboard。
更新:
要将ContentPresenter 切换为ContentControl,只需在ControlTemplate 中将实际元素切换为新元素即可。
<ControlTemplate TargetType="{x:Type Button}">
...
<ContentPresenter x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" RecognizesAccessKey="True"/>
...
</ControlTemplate>
到:
<ControlTemplate TargetType="{x:Type Button}">
...
<ContentControl x:Name="contentPresenter" Focusable="False" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Content="{TemplateBinding Content}"/>
...
</ControlTemplate>
您必须相应地更新它们的属性,例如ContentControl 不支持RecognizesAccessKeys,它还需要在其上设置Content="{TemplateBinding Content}" 才能实际显示内容。对于ContentPresenter,Content 属性是隐式设置的。