在XAML中,我有这样的代码:
<Style TargetType="Button">
<Setter Property="Foreground" Value="#c10000" x:Name="TextColor"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="RootElement" CornerRadius="8">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver">
<Storyboard>
<ColorAnimation Storyboard.TargetName="TextColor"
Storyboard.TargetProperty="Foreground" To="#FF8D00" />
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
此代码失败,并显示在边框的名称范围内未找到“TextColor”的消息。如何访问定义TextColor的名称范围呢? ColorAniamtion应该使用foreground属性访问setter并更改颜色。
答案 0 :(得分:0)
为按钮的Foreground
属性设置动画,而不是为Setter
设置动画。由于Foreground
属性的类型为Brush
,而不是Color
,因此我在下面的示例代码中使用对象动画而不是颜色动画:
<Button.Style>
<Style TargetType="Button">
<Setter Property="Foreground" Value="#c10000"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="RootElement" CornerRadius="8">
<ContentPresenter/>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="MouseOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(Button.Foreground)">
<ObjectAnimationUsingKeyFrames.KeyFrames>
<DiscreteObjectKeyFrame KeyTime="0:0:0">
<DiscreteObjectKeyFrame.Value>
<SolidColorBrush Color="#FF8D00"/>
</DiscreteObjectKeyFrame.Value>
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames.KeyFrames>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Style>