簡體   English   中英

在for循環中對WPF控件進行動畫處理

[英]Animate wpf control in a for loop

我正在嘗試實現一個動畫,在其中我使用for循環將控件從一行移到另一行。

    private void AnimateStoryBoard(int number)
    {
        Storyboard _currentStoryBoard = new Storyboard();

       //Row Animation
        Int32Animation newrowanimation = new Int32Animation();
        newrowanimation.From = number;
        newrowanimation.To = number+1;
        newrowanimation.Duration = new TimeSpan(0, 0, 0, 0, 500);

        Storyboard.SetTargetProperty(newrowanimation, new PropertyPath("(Grid.Row)"));

        _currentStoryBoard.Children.Add(newrowanimation);

        Storyboard.SetTarget(newrowanimation, myrectangle);

        _currentStoryBoard.Begin();
    }

我用它來稱呼它

        for (int i = 0; i < 10; i++)
        {
            AnimateStoryBoard(i);
        }

現在,當我運行該動畫時,我希望動畫從1變到2,然后從2變到3,再從3變到4 ... 9-10。 但是,動畫直接跳到9,然后跳到10。

另外,如何在XAML中執行此操作?請注意,這里的數字10僅是一個示例。該數字必須來自代碼隱藏,並且會不斷變化。

正如亞歷山大·克萊爾(Alexander Clare)在評論中提到的那樣,您必須在情節提要中設置幾個動畫。 您使用循環的解決方案不起作用,因為您的方法在運行循環時不會返回,因此UI線程將無法呈現情節提要/動畫引起的更改。

一種解決方案是在一個Storyboard實例中包含可變數量的動畫(每行一個動畫)。 使用BeginTime屬性來交錯動畫。 我建議您在這些動畫之間使用40ms到100ms之間的值(我不會低於20ms)。

在代碼中,這看起來像這樣:

private void AnimateStoryboard(int number)
{
    // Create the storyboard that will be played
    var storyboard = new Storyboard();

    // Create the animation objects for each row change and add them to the storyboard
    var currentBeginTime = TimeSpan.Zero;
    for (var i = 0; i < number; i++)
    {
        var animation = new Int32Animation();
        // Set all the properties that you set on your animation objects before, and additionally use BeginTime
        animation.BeginTime = currentBeginTime;
        storyboard.Children.Add(animation);

        // Update the currentBeginTime to achieve the staggering effect
        currentBeginTime += TimeSpan.FromMilliseconds(50);
    }

    // Finally, start the Storyboard to run all animations
    storyboard.Begin();

}

恕我直言,無需重新發明輪子: 關鍵幀動畫也用於此目的。

因此,要創建所需的動畫,可以使用以下方法:

Storyboard storyBoard = new Storyboard();
int gridRowLimit = 5; // here you can set how many rows your grid has

Int32AnimationUsingKeyFrames intKeyFrame = new Int32AnimationUsingKeyFrames();
intKeyFrame.Duration = new TimeSpan(0, 0, 0, 0, gridRowLimit * 500);

for (int i = 1; i < gridRowLimit; i++)
{
    intKeyFrame.KeyFrames.Add(new DiscreteInt32KeyFrame(i));
}

Storyboard.SetTargetProperty(intKeyFrame, new PropertyPath("(Grid.Row)"));
Storyboard.SetTarget(intKeyFrame, yourControl);

storyBoard.Children.Add(intKeyFrame);
storyBoard.Begin();

希望對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM