System.InvalidOperationException - 添加动态countdate

时间:2017-09-12 17:23:20

标签: c# wpf animation

我试图提供很多时间计数器,这是我的代码:

for(int i=0;i<10;i++)
{
long date=8000;
TextBlock tx = new TextBlock();
tx.Name="txt"+i;
CountDateLoad(date,tx);
grid.Children.Add(tx);
}

void CountDateLoad(long dt, TextBlock tx )
        {
            var countdownAnimation = new StringAnimationUsingKeyFrames();

            for (var i = dt; i > 0; i--)
            {
                var keyTime = TimeSpan.FromSeconds(dt - i);
                string result = CountDate(i);
                var frame = new DiscreteStringKeyFrame(result, KeyTime.FromTimeSpan(keyTime));
                countdownAnimation.KeyFrames.Add(frame);
            }
            countdownAnimation.KeyFrames.Add(new DiscreteStringKeyFrame(" ", KeyTime.FromTimeSpan(TimeSpan.FromSeconds(6))));
           Storyboard.SetTargetName(tx.Name);
            Storyboard.SetTargetProperty(countdownAnimation, new PropertyPath(TextBlock.TextProperty));

            var countdownStoryboard = new Storyboard();
            countdownStoryboard.Children.Add(countdownAnimation);
            //  countdownStoryboard.Completed += CountdownTimer_Completed;

            countdownStoryboard.Begin(this);
        }


  private string CountDate(long p)
        {
            long hour = p / 3600;
            long minute = (p - (hour * 3600)) / 60;
            long second = p % 60;
            string result = "";
            if (hour < 10) result += "0";
            result += hour + " : ";
            if (minute < 10) result += "0";
            result += minute + " : ";
            if (second < 10) result += "0";
            result += second;
            return result;
        }

这是错误:

  

类型&#39; System.InvalidOperationException&#39;的例外情况发生在   PresentationFramework.dll但未在用户代码中处理

     

其他信息:&#39; txt0&#39;在名称范围中找不到名称   &#39; MainWindow&#39;。

1 个答案:

答案 0 :(得分:2)

对于StoryBoard tx.Name是不够的,您需要在Scope中注册要使用它的控件(文本框)名称。为此,您应该使用{{1}其中(someFrameworkElement).RegisterName(Name,element)是范围。以下是示例:sample和msdn reference