需要帮助通过计时器在c#中随机调用故事板

时间:2015-08-17 15:58:01

标签: c# wpf animation timer storyboard

好的,所以我有4个带有动画的故事板。我想随机调用它们,间隔为2秒。我尝试了以下内容,部分工作。

TargetAnimate和target4animation一起被调用两次。 target2animation和target4animation被一起调用两次。 target3animation被称为三次。

     namespace FF2D
{
    /// <summary>
    /// Interaction logic for Level1.xaml
    /// </summary>
    public partial class Level1 : UserControl
    {
        public Level1()
        {
            this.InitializeComponent();                      
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void UserControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            DispatcherTimer tgtTimer = new DispatcherTimer();
            tgtTimer.Tick += new EventHandler(tgtTimer_tick);
            tgtTimer.Interval = new TimeSpan(0, 0, 2);
            tgtTimer.Start();

        }

            private void tgtTimer_tick(Object sender, EventArgs e)
            {
                Random _t = new Random();
                int n = _t.Next(1, 4);
                if(n == 1)
                {
                    Storyboard sb1 = this.FindResource("TargetAnimate") as Storyboard;
                    sb1.Begin();
                }

                if(n == 2)
                {
                    Storyboard sb2 = this.FindResource("target2animation") as Storyboard;
                    sb2.Begin();
                }

                if(n == 3)
                {
                    Storyboard sb3 = this.FindResource("target3animation") as Storyboard;
                    sb3.Begin();
                }

                else
                {
                    Storyboard sb4 = this.FindResource("target4animation") as Storyboard;
                    sb4.Begin();
                }
            }

        }
}

1 个答案:

答案 0 :(得分:0)

如果n = 1,2或4,

target4animation将被启动。

更改else的{​​{1}}或添加elses:

if(n == 4)