WPF中如何给自定义依赖项属性设置动画效果,该属性是Brush类型
博轩 2018-03-19 10:19:53 在.cs中添加了自定义属性:
public static DependencyProperty CurrentForegroundProperty =
DependencyProperty.Register("CurrentForeground", typeof(Brush), typeof(Turnout), new PropertyMetadata((Brush)m_fwkElement.TryFindResource("@InitColor"), CurrentForegroundChanged));
public Brush CurrentForeground //[当前前景色]
{
get { return (Brush)GetValue(CurrentForegroundProperty); }
set { SetValue(CurrentForegroundProperty, value); }
}
private static void CurrentForegroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Brush NewBrush = (Brush)e.NewValue;
Brush OldBrush = (Brush)e.OldValue;
Turnout turnout = d as Turnout;
turnout.HistoryForeground = OldBrush;
turnout.CurrentForeground = NewBrush;
}
在.XAML对其前景色进行了绑定:
<Style TargetType="{x:Type local:Turnout}">
<Setter Property="Background" Value="{x:Null}"/>
<Setter Property="Foreground" Value="{Binding RelativeSource={RelativeSource Self}, Path=CurrentForeground,Mode=TwoWay}"/>
<Setter Property="BorderBrush" Value="{x:Null}"/>
<Setter Property="Height" Value="22"/>
<Setter Property="Width" Value="20"/>
<Setter Property="Template" Value="{StaticResource TurnoutTemplate}"/>
</Style>
在模板TurnoutTemplate中对自定义属性进行动画处理:
<Storyboard>
<ColorAnimationUsingKeyFrames RepeatBehavior="Forever" BeginTime="00:00:00" Storyboard.TargetProperty="(Control.Foreground).(SolidColorBrush.Color)">
<DiscreteColorKeyFrame Value="Red" KeyTime="00:00:0.3" />
<DiscreteColorKeyFrame Value="Transparent" KeyTime="00:00:0.6" />
</ColorAnimationUsingKeyFrames>
</Storyboard>
在调试时会报异常:无法对不可变对象实例上的“(0).(1)”进行动画处理。
这是怎么回事儿啊?求大神帮帮忙,动画效果应该怎么写啊?