故事板可以在不启动的情况下进行控制吗?

时间:2016-01-13 22:34:45

标签: c# wpf xaml storyboard

我想在C#中启动它之前检查Storyboard是否已经启动。当然,如果您未使用GetCurrentState(),任何使用GetCurrentProgress()storyboardInstance.Begin(FrameworkElement, FrameworkElementTemplate, isControllable)的尝试都会导致异常。问题是我不想启动故事板。

关于这个主题的文档相当薄,Google查询产生的结果很少,所以我只能假设我滥用这个功能。检查我能想到的状态的唯一方法是捕获异常,但这看起来非常可怕。

那里有更好的想法吗?

满足要求的示例

<TextBlock x:Name="textBlock">
  <TextBlock.Triggers>
    <EventTrigger RoutedEvent="SomeFakeEventICreated">
      <BeginStoryboard x:Name="storyBoard">
        <Storyboard>
          <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:10"
                                         Storyboard.TargetName="BackgroundLogo"
                                         Storyboard.TargetProperty="Opacity">
                                <EasingDoubleKeyFrame KeyTime="00:00:00.0" Value="1" />
                                <EasingDoubleKeyFrame KeyTime="00:00:10" Value="1" />
          </DoubleAnimationUsingKeyFrames>
        </Storyboard>
      </BeginStoryboard>
    </EventTrigger>
  </TextBlock.Triggers>
<TextBlock>

public void DoSomethingStoryboardy(){
  // EXAMPLE OF FAILURE
  if (GetProgress() == 0.0d) // Exception
    BeginStoryboard(); 

  // EXAMPLE OF SUCCESS
  // but what a shameful way to do this
  double progress = 0.0d;
  try { 
    progress = GetProgress();
  } catch { }
  if (progress == 0.0d)
    BeginStoryboard();
  else PauseStoryboard();
}

public void GetProgress() {
   // Pass in containing object 
   double progress = storyBoard.Storyboard.GetCurrentProgress(textBlock);
   // Exception is thrown: Cannot perform action because the specified Storyboard was not applied to this object for interactive control.
   // This behavior is exactly as you'd expect, because the documentation states it needs to be controllable before you can call any of these "Get...()" methods. 
}

public void BeginStoryboard() {
  // Only Begin() allows setting IsControllable
  storyBoard.Storyboard.Begin(containingObject: textBlock, frameworkElementTemplate: null, isControllable: true);
  // Storyboard control after Begin() works fine because it has started already
  double progress = storyBoard.Storyboard.GetCurrentProgress(textBlock);
}

public void PauseStoryboard() {
  storyBoard.Storyboard.Pause(textBlock);
}

2 个答案:

答案 0 :(得分:0)

解决方法是在不启动故事板状态的情况下查询故事板状态的唯一方法。之前在C#中使用IsControllable覆盖 的任何尝试查询故事板(使用storyboard.Get...())都会导致异常。根据我对MSDN文档的研究,以下代码尽可能接近。

代码

double progress = 0.0d;
try { 
  progress = GetProgress(); // Query storyboard status
} catch {
  // Do nothing if the exception is thrown, we knew this would happen
}
if (progress == 0.0d)
  BeginStoryboard();
else PauseStoryboard();

答案 1 :(得分:0)

订阅Storyboard&#39; CurrentStateInvalidated活动。一旦调用它(第一次转到Active),您就知道Storyboard已经启动。设置一个标志来记住它。显然,在那之前它还没有运行(你的旗帜是假的)。

相关问题