扩展WPF动画类的奥秘
问题描述:
Silverlight在其动画时间轴(如DoubleAnimation)上有一个名为EasingFunction的属性,它允许您指定一个函数来插入两个值。即使它使用.NET 4,我也想把它移植到3.5。在阅读this后,它看起来非常可行,但我有一个奇怪的问题。扩展WPF动画类的奥秘
我伸出DoubleAnimation是像这样:
class EasingDoubleAnimation : DoubleAnimation
{
protected override Freezable CreateInstanceCore()
{
return new EasingDoubleAnimation();
}
protected override double GetCurrentValueCore(double defaultOriginValue, double defaultDestinationValue, AnimationClock animationClock)
{
Debug.WriteLine(animationClock.CurrentProgress.Value);
return base.GetCurrentValueCore(defaultOriginValue, defaultDestinationValue, animationClock);
}
public EasingFunctionBase EasingFunction
{
get { return (EasingFunctionBase) GetValue(EasingFunctionProperty); }
set { SetValue(EasingFunctionProperty, value); }
}
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register("EasingFunction", typeof(EasingFunctionBase), typeof(EasingDoubleAnimation),
new PropertyMetadata(null));
}
注意,它没有做什么有趣的除了添加新的属性。
,然后我可以在一些代码中使用它:
Storyboard sb = new Storyboard();
EasingDoubleAnimation ease = new EasingDoubleAnimation();
//ease.EasingFunction = new BackEase();
Storyboard.SetTarget(ease, MyTarget);
Storyboard.SetTargetProperty(ease, new PropertyPath("(Canvas.Left)"));
ease.To = 100;
ease.Duration = TimeSpan.FromSeconds(3);
sb.Children.Add(ease);
sb.Begin();
运行代码的动画就好了。
但是,如果我取消注释设置EasingFunction的行,动画不再运行。我的CreateInstanceCore方法被调用,但GetCurrentValue永远不会被调用。奇怪的?
答
只是要在黑暗中拍摄这里。尝试将属性的类型更改为简单类型(int
/string
)。我怀疑这可能与您的房产类型为EasingFunctionBase
并且您试图冻结实例有关。
我实际上已经在发布之前进行了实验,发现只要我有简单的属性类型,一切正常。它看起来像你在Freezable对象上不能有复杂的属性类型。 “那么Silverlight 3如何做到这一点?”我问,并且我在Reflector中发现SL3中的DoubleAnimation实际上不像WPF中的Freezable。似乎我可能无法以明显的方式做我想做的事。 – 2009-10-17 19:38:28
除非我使EasingFunctionBase也可以冻结。然后它就可以工作了,尽管我以后不能更改它的属性......但对我而言,这可能还行。谢谢回复。 – 2009-10-17 19:41:43