【问题标题】:WP8.1: Start an animation from the current locationWP8.1:从当前位置开始动画
【发布时间】:2014-09-19 14:42:04
【问题描述】:

我希望控件根据另一个属性更改其位置,但动画到该新位置。但是,每当我启动新动画时,故事板都会将控件的位置重置为 XAML 中设置的属性。

这就是我正在做的事情:

var animation = new DoubleAnimation();
animation.Duration = TimeSpan.FromSeconds(0.1);

// This gets the value that was set in the XAML, not the current value         
// animation.From = Canvas.GetLeft(BackgroundImage);
animation.To = newLocation;

Storyboard.SetTarget(animation, BackgroundImage);
Storyboard.SetTargetProperty(animation, "(Canvas.Left)");

Storyboard story = new Storyboard();
story.Children.Add(animation);
story.Begin();

有没有办法从控件获取当前动画值以设置为动画。从,或者有没有办法告诉故事板从当前属性的位置开始?

【问题讨论】:

    标签: c# xaml animation windows-phone-8.1


    【解决方案1】:

    如果你想为Canvas.Left属性设置动画,From的值确实是

    Canvas.GetLeft(BackgroundImage)
    

    但是,如果不指定 From 属性(就像您注释掉它的方式一样),Storyboard 应该从当前位置开始。所以你真的不需要上面的代码。

    我觉得你的动画很好。可能是其他原因导致了问题。


    更新

    这是一个工作示例,当属性发生更改时,控件会被动画到相应的位置。

    在我的 xaml 中,我创建了一个 Slider 控件,并且每次更改 SliderValue 时,我想将我的 BackgroundImage 控件的 Canvas.Left 设置为这个 Value 的动画。这有点像您在问题中提到的另一个属性

    Xaml

    <Slider x:Name="MySlider" Margin="12,0" VerticalAlignment="Bottom" Minimum="20" Maximum="220" SmallChange="10" Value="20" />
    

    守则

    private Storyboard _storyboard = new Storyboard();
    private DoubleAnimation _animation = new DoubleAnimation { Duration = TimeSpan.FromSeconds(0.1) };
    
    public MainPage()
    {
        this.InitializeComponent();
    
        Storyboard.SetTarget(_animation, this.BackgroundImage);
        Storyboard.SetTargetProperty(_animation, "(Canvas.Left)");
        _storyboard.Children.Add(_animation);
    
        this.MySlider.ValueChanged += (s, e) =>
        {
            _animation.To = this.MySlider.Value;
            _storyboard.Begin();
        };
    }
    

    如您所见,我为StoryboardDoubleAnimation 实例保留了两个局部变量。然后在调用ValueChanged 时,只需设置To 并启动动画。

    【讨论】:

    • 当我一直在测试时,Canvas.GetLeft 总是返回 XAML 中设置的值,而不是故事板中设置的当前值。如果我开始一个新的故事板,它总是将 Left 值重置为 XAML 中设置的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-07
    • 2010-12-13
    相关资源
    最近更新 更多