我无法在WPF中设置自定义属性的动画

时间:2010-10-10 00:15:16

标签: wpf animation

我几个小时都在苦苦挣扎,我无法找出我做错了什么。请帮我找错。

我创建了一个带有一个自定义依赖项属性的用户控件,我想为此属性设置动画。

这是我的班级:

public partial class UserControl1 : UserControl
{
    public UserControl1()
    {
        InitializeComponent();
    }

    public long Val
    {
        get { return (long)GetValue(ValProperty); }
        set {
             SetValue(ValProperty, value);

             // Update a text block for debug
             ((Class1)this.Resources["class1"]).Val = value;  
        }
    }

    public static readonly DependencyProperty ValProperty =
        DependencyProperty.Register("Val", typeof(long), typeof(UserControl1), new UIPropertyMetadata(0L));
}

以下是应该为其设置动画的代码(有一个名为usercontrol11的UserControl1实例):

        Int64Animation myAnimation = new Int64Animation();
        myAnimation.From = 100;
        myAnimation.To = 200;
        myAnimation.Duration = new Duration(TimeSpan.FromSeconds(1));

        Storyboard.SetTargetName(myAnimation, userControl11.Name);
        Storyboard.SetTargetProperty(myAnimation, new PropertyPath(UserControl1.ValProperty));

        Storyboard myStoryboard = new Storyboard();
        myStoryboard.Children.Add(myAnimation);
        myStoryboard.Begin(this);

我也尝试了XAML方法,但它也没有用(在下面的XAML中,Width动画工作正常,但Val没有):

<my:UserControl1 HorizontalAlignment="Left" Width="150" Margin="72,45,0,0" x:Name="userControl11" VerticalAlignment="Top" Background="#FFFFD100">
  <my:UserControl1.Triggers>
    <EventTrigger RoutedEvent="MouseEnter">
        <EventTrigger.Actions>
            <BeginStoryboard>
                <Storyboard>
                    <Int64Animation To="300" Duration="0:0:1"
                                    Storyboard.TargetProperty="Val" />
                    <DoubleAnimation To="300" Duration="0:0:1"
                                    Storyboard.TargetProperty="Width" />
                </Storyboard>
            </BeginStoryboard>
        </EventTrigger.Actions>
    </EventTrigger>                        
  </my:UserControl1.Triggers>
</my:UserControl1>

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

嗯,它实际上是动画的。你只是在错误的地方检查,动画不会调用Val属性集访问器。例如,您可以覆盖OnPropertyChanged方法来查看更改:

    protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
    {
        base.OnPropertyChanged(e);
        if(e.Property == ValProperty)
        {
            MessageBox.Show(e.NewValue.ToString());
        }
    }