WPF改变方向DoubleAnimation

时间:2012-08-22 19:06:13

标签: c# .net wpf

我在画布中有如下图像:

<Canvas x:Name="cnvMain"  ClipToBounds="True" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  SnapsToDevicePixels="True">
    <Image x:Name="Image1"   Stretch="None" Canvas.Bottom="0"  Source="ImageGallery/Desert.jpg" ></Image>
</Canvas>

对于上下移动图像,我使用了DoubleAnimation,如下所示:

 DoubleAnimation _Animation;
    private Storyboard _StoryBoard;

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        Canvas.SetZIndex(Image1, 1);

        _Animation = new DoubleAnimation();
        _Animation.From = -Image1.ActualHeight;
        _Animation.To = cnvMain.ActualHeight;
        _Animation.RepeatBehavior = RepeatBehavior.Forever;
        _Animation.Duration = new Duration(TimeSpan.Parse("0:0:10"));
        _Animation.FillBehavior = FillBehavior.Stop;
        Storyboard.SetTarget(_Animation, Image1);
        Storyboard.SetTargetProperty(_Animation, new PropertyPath(Canvas.BottomProperty));
        _StoryBoard = new Storyboard();
        _StoryBoard.Children.Add(_Animation);
        _StoryBoard.Begin();
        _StoryBoard.Pause();
    }
    public void Pause()
    {
        _StoryBoard.Pause();
    }
    public void Up()
    {
        _Animation.From = cnvMain.ActualHeight;
        _Animation.To = -Image1.ActualHeight;
        _StoryBoard.Resume();

    }
    public void Down()
    {
        _Animation.From = Image1.ActualHeight;
        _Animation.To = -cnvMain.ActualHeight;
        _StoryBoard.Resume();

    }

使用From和To在UserControl_Loaded中初始化动画。我的问题是这个属性在Down和Top方法调用中没有改变(方法有效但图像向上移动)

1 个答案:

答案 0 :(得分:0)

我将其改为喜欢以下并且有效。

DoubleAnimation _Animation;
    private Storyboard _StoryBoard;

    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        LoadAnimaiton(false);
        _StoryBoard.Pause();
    }

    private void LoadAnimaiton(bool up)
    {
        _StoryBoard = new Storyboard();
        _Animation = new DoubleAnimation(100.0, new Duration(TimeSpan.Parse("0:0:10")));
        _Animation.From = cnvMain.ActualHeight;
        _Animation.To = -Image1.ActualHeight;
        _Animation.RepeatBehavior = RepeatBehavior.Forever;
        _Animation.FillBehavior = FillBehavior.Stop;
        Storyboard.SetTarget(_Animation, Image1);
        Storyboard.SetTargetProperty(_Animation, new PropertyPath(Canvas.BottomProperty));

        if (up)
        {
            _Animation.From = cnvMain.ActualHeight;
            _Animation.To = -cnvMain.ActualHeight;
        }
        else
        {
            _Animation.From = -cnvMain.ActualHeight;
            _Animation.To = cnvMain.ActualHeight;
        }

        _StoryBoard.Children.Add(_Animation);

        _StoryBoard.Begin();
    }
    public void Pause()
    {
        _StoryBoard.Pause();
    }
    public void Down()
    {
        LoadAnimaiton(true);
    }

    public void Up()
    {
        LoadAnimaiton(false);
    }