以特定时间间隔添加动画

时间:2012-04-06 21:18:50

标签: c# wpf animation

我对动画相对较新,所以我正在寻找一些方向。我们说我有List<Label>,其中加载了15个标签。我有DoubleAnimation在500毫秒内将不透明度从m 0设置为1。我想循环,这些标签每1000毫秒开始动画。因此label1从0ms开始,label2从1000ms开始等。

我知道我可以将Storyboard.Duration设置为1000毫秒* 15并将我的标签添加到SB并开始播放,但动画的播放速度与添加到SB的速度一样快。有没有办法以特定的时间间隔将动画添加到SB?

修改 我不再使用List<Label>了 这是我写的代码

class MessageWriter
{
    Storyboard _sb = new Storyboard();
    public MessageWriter()
    {

    }

    public void ProcessMessage(string _Message, WrapPanel _Panel)
    {
        string[] _Words = _Message.Split(new char[1]{Convert.ToChar(" ")});
        int _Counter = 1;
        _sb = new Storyboard();
        foreach (string _Word in _Words)
        {
            _Panel.Children.Add(ProcessWord(_Word));
            if (_Counter < _Words.Length)
            {
                _Panel.Children.Add(ProcessWord(" "));
            }
            _Counter++;
        }
        _sb.Begin();
    }

    private StackPanel ProcessWord(string _Word)
    {
        Debug.Print(_Word);
        StackPanel _Panel = new StackPanel();
        _Panel.Orientation = Orientation.Horizontal;
        _Panel.Margin = new System.Windows.Thickness(0, 0, 0, 0);

        foreach (char _c in _Word.ToList())
        {
            Label _Label = new Label();
            _Label.Opacity = 0;
            _Label.Margin = new System.Windows.Thickness(0, 0, 0, 0);
            _Label.Padding = new System.Windows.Thickness(0, 0, 0, 0);
            _Label.Content = _c.ToString();
            _Panel.Children.Add(_Label);
            AnimateLabel(_Label);
        }
        return _Panel;
    }

    private void AnimateLabel(Label _Label)
    {
        DoubleAnimation _da = new DoubleAnimation();
        _da.From = 0;
        _da.To = 1;

        int _MillSec = 500;
        _da.Duration = new System.Windows.Duration(new TimeSpan(0, 0, 0, 0, _MillSec));

        Storyboard.SetTargetProperty(_da, new PropertyPath(FrameworkElement.OpacityProperty));
        Storyboard.SetTarget(_da, _Label);
        _sb.Children.Add(_da);
    }
}

1 个答案:

答案 0 :(得分:3)

您只需设置每个动画的BeginTime即可。

并且绝对不需要故事板。只需将动画应用于标签:

DoubleAnimation opacityAnimation = new DoubleAnimation
{
    To = 1d,
    Duration = TimeSpan.FromSeconds(0.5),
    BeginTime = TimeSpan.FromSeconds((double)labelIndex)
};
labelIndex++;
label.BeginAnimation(UIElement.OpacityProperty, opacityAnimation);

为什么这个奇怪的下划线在每个变量名称上?人们普遍接受.Net naming conventions