自定义DependencyProperty不更新动画

时间:2014-10-03 13:06:34

标签: windows-runtime winrt-xaml

我正在将应用程序从Windows Phone 8(Silverlight)移植到WinRT-XAML。我创建了一个自定义DependecyProperty,我使用DoubleAnimation进行动画制作。这可以在WP8上找到,但在WinRT版本上不起作用。

该物业本身确实有效;如果我在代码中手动设置其值,则调用更改回调并且一切正常。动画似乎也在运行;它持续指定的持续时间,然后使用AnimCompleted回调完成 - 但DependencyProperty未更新,也未调用其更改回调。我创建了一个计时器,在动画运行时打印出动画属性的值,并保持不变。

我做错了什么?与WP8相比,WinRT有何不同?

属性定义:

public static readonly DependencyProperty MyPropProperty =
    DependencyProperty.Register( "MyProp", typeof(double), typeof(MyClass),
                                 new PropertyMetadata( 1d, OnMyPropChanged ));

public double MyProp
{
    get { return (double)GetValue( MyPropProperty ); }
    set { SetValue( MyPropProperty, value ); }
}

private static void OnMyPropChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
{
    var m = d as MyClass;
    System.Diagnostics.Debug.WriteLine( "Value now: " + m.MyProp );
}

XAML:

<Storyboard x:Name="AnimSB" Completed="AnimCompleted">
    <DoubleAnimation x:Name="Anim" Storyboard.TargetProperty="MyProp" Duration="0:0:1.00">
        <DoubleAnimation.EasingFunction>
            <QuadraticEase EasingMode="EaseInOut"/>
        </DoubleAnimation.EasingFunction>
    </DoubleAnimation>
</Storyboard>

启动动画的代码:

MyProp = 2.0; // this causes a call to OnMyPropChanged just fine
Anim.From = 2.0;
Anim.To = 1.0;
Storyboard.SetTarget( Anim, this );
AnimSB.Begin();
// after this, MyProp stays constant, OnMyPropChanged is not called,
// and AnimCompleted is called after exactly one second.

1 个答案:

答案 0 :(得分:4)

您需要在动画上将EnableDependentAnimation设置为true。原因是不鼓励在UI线程(依赖属性)上更改的动画属性,从而产生不连贯的动画。建议仅为RenderTransform属性或Opacity等独立属性制作动画,而不是WidthMarginCanvas.X等自定义属性或自定义属性