停止WPF动画,故事板在xaml中开始但在代码隐藏中停止吗?

我在xaml文件中创建了一个动画故事板。 那个故事板开始于Button.Click。 但是为了停止动画,我试图在代码背后的自定义事件上停止故事板。 代码没有抛出任何exception但是当我的事件被触发时,动画仍然继续。

我认为问题在于Stop方法。 停止需要与开始动画相同的对象来停止它。 但是这里的故事板是从WPF xaml开始的,我在后面的代码中停止它。

任何解决方案,如何在代码中获取Xaml对象或任何替代解决方案?

XAML代码:

             

代码背后:

  private void EventPublisher_OnScanningFinish(object sender, EventArgs args) { Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate() { this.StopScanningAnimation(); }); } private void StopScanningAnimation() { ServerView.StoryBoardServerScrolling.Stop(this); //---------- Not Working //this.ServerView.Server1Static.Visibility = System.Windows.Visibility.Hidden; //this.ServerView.Server2Static.Visibility = System.Windows.Visibility.Hidden; //this.ServerView.Server3Scrolling.Visibility = System.Windows.Visibility.Hidden; //this.ServerView.SearchingGlass.Visibility = System.Windows.Visibility.Hidden; } 

将故事板定义为静态资源,

         

并从您的后端代码引用它,如下所示:

 StoryBoard board = (StoryBoard)this.FindResource("MovingServer"); board.stop(); 

从按钮的“click”事件开始动画(我不知道你是否在xaml中定义了,但是如果你这样做的话,这是怎么做的)

  protected void Scanbutton_Click(object Sender, EventArgs e) { StoryBoard board = (StoryBoard)this.FindResource("MovingServer"); board.start(); } 

我使用Storyboard类的Stop()方法解决了这个问题

 myStoryBoard.Stop(this.LayoutRoot); 

使用此解决方案,您无需在资源中声明Storyboard。

我很感谢提摩太给出了很好的想法。 我在这里发布我的工作代码

  /*create this resources as global to that perticular xaml. Need not to be put it in App.xaml MyControl could be Window or Page or UserControl */         /*  */ /*  */        /* ****************************************************************** */ /* Code behind to start/stop animation*/ //Get the resource value first on current object, so that when you start/stop the animation, it work only on current object Storyboard sbImageAnimate = (Storyboard)this.ServerView.FindResource("MovingServer"); //Start the animation on Button Click protected void Scanbutton_Click(object Sender, EventArgs e) { this.MyImage.Visibility = System.Windows.Visibility.Visible; sbImageAnimate.Begin(); } //Stop animation on my own even. You can use it on any event private void EventPublisher_OnFinish(object sender, EventArgs args) { Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate() { this.StopScanningAnimation(); }); } private void StopScanningAnimation() { sbImageAnimate.Stop(); this.MyImage.Visibility = System.Windows.Visibility.Hidden; }