为什么自定义依赖项属性不是DoubleAnimation的动画?

时间:2013-05-15 10:51:55

标签: c# .net wpf animation dependency-properties

我有以下WPF窗口:

<Window x:Class="AnimationTest.MainWindow"
    x:Name="main"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" >

<Window.Resources>
    <Storyboard RepeatBehavior="Forever" x:Key="animationStoryboard" TargetName="main" TargetProperty="CurrentOffset" >
        <DoubleAnimation From="0" To="100" Duration="0:0:5"  SpeedRatio=".8" AutoReverse="True" />
    </Storyboard>
</Window.Resources>

<Grid>

</Grid>
</Window>

后面的代码如下:

using System.Windows;
using System.Windows.Media.Animation;

namespace AnimationTest
{
public partial class MainWindow : Window
{
    public static DependencyProperty CurrentOffsetProperty = DependencyProperty.Register("CurrentOffset", typeof(double), typeof(MainWindow), new FrameworkPropertyMetadata(OnCurrentOffsetPropertyChanged));

    private static void OnCurrentOffsetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        MainWindow control = (MainWindow)d;
    }

    public double CurrentOffset
    {
        get
        {
            return (double)base.GetValue(MainWindow.CurrentOffsetProperty);
        }
        set
        {
            MessageBox.Show("Hit");
            base.SetValue(MainWindow.CurrentOffsetProperty, value);
        }
    }

    public MainWindow()
    {
        InitializeComponent();

        ((Storyboard)base.FindResource("animationStoryboard")).Begin(this);
    }
}
}

我希望连续调用CurrentOffset属性,但没有任何反应。这就像动画无法启动。任何人都可以指出我在哪里错了?

提前致谢。

2 个答案:

答案 0 :(得分:1)

添加到我之前的评论和@Clemens

我自己尝试过你的代码并且工作正常。您将不得不在PropertyChanged处理程序中“工作”,但DP可以按预期工作。

我修改了你的故事板,不再重复测试DP值,如:

<Storyboard x:Key="animationStoryboard"
            TargetProperty="CurrentOffset"
            TargetName="main">
  <DoubleAnimation Duration="0:0:5"
                    From="0"
                    SpeedRatio=".8"
                    To="100" />
</Storyboard>

和代码隐藏:

public MainWindow() {
  InitializeComponent();
  var sb = ((Storyboard)base.FindResource("animationStoryboard"));
  sb.Completed += (sender, args) => MessageBox.Show(CurrentOffset.ToString());
  sb.Begin();
}

MessageBox的调用值为99.8888 ......看起来它的工作正常。

答案 1 :(得分:0)

您作为DependencyProperty的包装器编写的属性将不会被WPF调用。它将直接转到您的DependencyObject。您可以像往常一样将回调传递给DependencyObject注册,应该被调用。你可能想在那里调试。