首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >System.Invalid.Operation.Exception

System.Invalid.Operation.Exception
EN

Stack Overflow用户
提问于 2019-04-15 21:42:51
回答 1查看 275关注 0票数 1

我试图把一个动画在wpf上的一个编程文本块。

但我得到了一个System.InvalidOperationException

好的,代码在由xaml组成的文本块中工作,所以我怀疑它是不是代码。

代码语言:javascript
复制
private void TypewriteTextblock(string textToAnimate, TextBlock txt, TimeSpan timeSpan)
{
    Storyboard story = new Storyboard();
    story.FillBehavior = FillBehavior.HoldEnd;

    discreteStringKeyFrame = null;
    StringAnimationUsingKeyFrames stringAnimationUsingKeyFrames = new StringAnimationUsingKeyFrames();
    stringAnimationUsingKeyFrames.Duration = new Duration(timeSpan);

    string tmp = string.Empty;
    foreach (char c in textToAnimate)
    {
        discreteStringKeyFrame = new DiscreteStringKeyFrame();
        discreteStringKeyFrame.KeyTime = KeyTime.Paced;
        tmp += c;
        discreteStringKeyFrame.Value = tmp;
        stringAnimationUsingKeyFrames.KeyFrames.Add(discreteStringKeyFrame);
    }
    Storyboard.SetTargetName(stringAnimationUsingKeyFrames, txt.Name);
    Storyboard.SetTargetProperty(stringAnimationUsingKeyFrames, new PropertyPath(TextBlock.TextProperty));
    story.Children.Add(stringAnimationUsingKeyFrames);
    story.Begin(txt); //Here i got the Exception
}

下面是我创建Textblock的方法:

代码语言:javascript
复制
for (int i = 1; i <= juego.PreguntaActiva.NumeroRespuestas(); i++)
{
    TextBlock tb = new TextBlock() { Name = "res" + i, FontSize = 24, Foreground = Brushes.White, Margin = new Thickness(10, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center, Text = i + "-" };
    tb.MouseLeftButtonDown += Tb_MouseLeftButtonDown;
    Grid.SetRow(tb, i);
    mainGrid.Children.Add(tb);
}

以及如何调用该方法

代码语言:javascript
复制
private void Tb_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    var textblock = (TextBlock)sender;
    var pos = int.Parse(textblock.Name.Substring(3, 1));
    TypewriteTextblock(juego.PreguntaActiva.Respuestas[pos - 1].Contenido, textblock, TimeSpan.FromSeconds(0.5));
    StopTimer();
}

并由此生成XAML代码

代码语言:javascript
复制
<TextBlock x:Name="res1" MouseLeftButtonDown="Res1_MouseLeftButtonDown" Grid.Row="1" Foreground="White" Margin="10,0,0,0" FontSize="24" VerticalAlignment="Center"></TextBlock>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-15 21:54:25

使用Storyboard.SetTarget方法而不是Storyboard.SetTargetName

代码语言:javascript
复制
Storyboard.SetTarget(stringAnimationUsingKeyFrames, txt); //<--
Storyboard.SetTargetProperty(stringAnimationUsingKeyFrames, new PropertyPath(TextBlock.TextProperty));
story.Children.Add(stringAnimationUsingKeyFrames);
story.Begin(txt);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55690551

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档