Invoke methods at specific times using a Storyboard

醉酒当歌 提交于 2019-12-24 03:39:17

问题


I would like to utilize a Storyboard object to invoke methods at specific times. Specifically; I am trying to make a fireworks display, with a Firework user control that has a Fire method. I want to create several of these controls and call their Fire methods at specific times (just like a real show).

Normally, you would use a Storyboard to animate properties of an object over time. Is there a way to invoke a method instead?

Something like (pseudo-code of course):

<Storyboard>
    <MethodUsingKeyFrames>
         <MethodKeyFrame KeyTime="0:0:1" TargetName="Firework1" Method="Fire"/>
         <MethodKeyFrame KeyTime="0:0:2.5" TargetName="Firework2" Method="Fire"/>
    </MethodUsingKeyFrames>
</Storyboard>

I have considered just using a Timer on a high interval and doing the sequencing myself, but that seems like a hack; especially when we have such a nice existing way of doing it.

Note: Related to Use a storyboard to call a method in a usercontrol created dynamically ; the question (at face value) seems to be the same, but the answer has nothing to do with what I am trying to accomplish.


回答1:


Here is what I ended up going with:

Add a dependency property NeedsToFire to the user control (a bool). Then handle the PropertyChanged event (via the metadata) with a function like:

public bool NeedsToFire
{
   get { return (bool)GetValue(NeedsToFireProperty); }
   set { SetValue(NeedsToFireProperty, value); }
}

public static readonly DependencyProperty NeedsToFireProperty =
        DependencyProperty.Register("NeedsToFire", typeof(bool), 
            typeof(Firework), new PropertyMetadata(false, HandleNeedsToFire));

private static void HandleNeedsToFire(DependencyObject d, 
                                      DependencyPropertyChangedEventArgs e)
{
   if ((bool)e.NewValue)
   {
      (d as Firework).Fire();
   }
}

Finally, use a BooleanAnimationUsingKeyFrames to set this property at the correct time:

<Storyboard x:Key="FireworksShow">
    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Firework1" 
                                    Storyboard.TargetProperty="NeedsToFire">
         <DiscreteBooleanKeyFrame KeyTime="0:0:0.5"  Value="True" />
    </BooleanAnimationUsingKeyFrames>
</Storyboard>

This seems like the easiest to implement solution; even if it does require using Dependency Properties in a way they weren't necessarily intended to be. It also allows for repeat firing.



来源:https://stackoverflow.com/questions/26663092/invoke-methods-at-specific-times-using-a-storyboard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!