【问题标题】:Create Storyboard from code behind in Uwp从 Uwp 中的代码创建故事板
【发布时间】:2020-04-27 12:29:13
【问题描述】:

我想从代码后面创建一个故事板,我想从代码后面实现下面的故事板,

 <Storyboard x:Name="Counter_Animation">
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="txtCounter" Storyboard.TargetProperty="(TextBlock.Text)">
            <DiscreteObjectKeyFrame KeyTime="00:00:01" Value="2"/>
            <DiscreteObjectKeyFrame KeyTime="00:00:02" Value="1"/>
            <DiscreteObjectKeyFrame KeyTime="00:00:03" Value="0"/>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>

我的页面上有一个名为 txtCounter 的 TextBlock,我已尝试从下面的代码中实现这一点,

private void CounterAnimation()
    {

        Storyboard storyboard = new Storyboard();
        ObjectAnimationUsingKeyFrames anim = new ObjectAnimationUsingKeyFrames();
        anim.BeginTime = TimeSpan.FromSeconds(0);
        DiscreteObjectKeyFrame keyFrames = new DiscreteObjectKeyFrame();
        keyFrames.KeyTime = TimeSpan.FromSeconds(1);
        keyFrames.Value = "2";
        keyFrames.KeyTime = TimeSpan.FromSeconds(2);
        keyFrames.Value = "1";
        keyFrames.KeyTime = TimeSpan.FromSeconds(3);
        keyFrames.Value = "0";
        anim.KeyFrames.Add(keyFrames);

        Storyboard.SetTarget(anim, txtCounter);
        Storyboard.SetTargetProperty(anim, "Text");

        storyboard.Children.Add(anim);

        storyboard.Begin();
    }

代码编译好并运行的问题是,在关键时间 1 txtCounter 应该显示 2,在关键时间 2 txtCounter 应该显示 1,在关键时间 3 txtCounter 应该显示 0 但是, 它直接向我显示 0(即不显示中间值)。 如果我犯了任何错误,请看一下并纠正我。这会有所帮助。谢谢

【问题讨论】:

  • 您需要向情节提要添加多个 DiscreteObjectKeyFrame 实例,就像 xaml 代码一样,而您只需添加一个值为 0 的实例。
  • 谢谢@MehrzadChehraz 我怎么错过了让我现在添加工作代码

标签: uwp uwp-xaml


【解决方案1】:

只是在这里写完整的代码,如果有人有更好的想法,请提出建议 这对我有用,

private Storyboard GetCounterAnimation()
    {

        Storyboard storyboard = new Storyboard();
        ObjectAnimationUsingKeyFrames counterAnimation = new ObjectAnimationUsingKeyFrames
        {
            BeginTime = TimeSpan.FromSeconds(0),
        };
        counterAnimation.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(1), Value = "2" });
        counterAnimation.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(2), Value = "1" });
        counterAnimation.KeyFrames.Add(new DiscreteObjectKeyFrame { KeyTime = TimeSpan.FromSeconds(3), Value = "Inhale" });
        Storyboard.SetTarget(counterAnimation, txtCounter);
        Storyboard.SetTargetProperty(counterAnimation, "Text");
        storyboard.Children.Add(counterAnimation);
        return storyboard;
    }

【讨论】:

    猜你喜欢
    • 2018-03-01
    • 1970-01-01
    • 2013-10-21
    • 2012-11-23
    • 2013-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多