我在xaml文件中创建了一个动画故事板.那个故事板开始于Button.Click.但是为了停止动画,我试图在代码背后的自定义事件上停止故事板.
代码没有抛出任何异常但是当我的事件被触发时,动画仍然继续.
代码没有抛出任何异常但是当我的事件被触发时,动画仍然继续.
我认为问题在于Stop方法.停止需要与开始动画相同的对象来停止它.但是这里的故事板是从WPF xaml开始的,我在后面的代码中停止它.
任何解决方案,如何在代码中获取Xaml对象或任何替代解决方案?
XAML代码:
<Canvas.Triggers> <EventTrigger RoutedEvent="Button.Click" SourceName="ScanButton"> <EventTrigger.Actions> <BeginStoryboard > <Storyboard Name="MovingServer" Storyboard.TargetName="ImageMove" RepeatBehavior="Forever" > <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:2" From="30" To="300" BeginTime="0:0:0" /> <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:5" From="300" To="300" BeginTime="0:0:5" /> <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:2" From="300" To="600" BeginTime="0:0:7" /> <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:2" From="1" To="0" BeginTime="0:0:7" /> </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger>
代码背后:
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; }
解决方法
将故事板定义为静态资源,
<MyControl.Resources> <Storyboard Key="MovingServer" Storyboard.TargetName="ImageMove" RepeatBehavior="Forever" > <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:2" From="30" To="300" BeginTime="0:0:0" /> <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:5" From="300" To="300" BeginTime="0:0:5" /> <DoubleAnimation Storyboard.TargetProperty="(Canvas.Left)" Duration="0:0:2" From="300" To="600" BeginTime="0:0:7" /> <DoubleAnimation Storyboard.TargetProperty="Opacity" Duration="0:0:2" From="1" To="0" BeginTime="0:0:7" /> </Storyboard> </MyControl.Resources>
并从您的后端代码引用它,如下所示:
StoryBoard board = (StoryBoard)this.FindResource("MovingServer"); board.stop();
从按钮的“click”事件开始动画(我不知道你是否在xaml中定义了,但是如果你这样做的话,这是怎么做的)
<Button x:Name="ScanButton" onClick="Scanbutton_Click"></button> protected void Scanbutton_Click(object Sender,EventArgs e) { StoryBoard board = (StoryBoard)this.FindResource("MovingServer"); board.start(); }