繁体   English   中英

System.Invalid.Operation.Exception

[英]System.Invalid.Operation.Exception

我试图在 wpf 上以编程方式制作的文本块上放置动画。

但我得到一个System.InvalidOperationException

好吧,代码在由 xaml 制作的文本块中工作,所以我怀疑它的代码。

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
}

这是我创建文本块的方式:

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);
}

以及我如何调用该方法

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 代码

<TextBlock x:Name="res1" MouseLeftButtonDown="Res1_MouseLeftButtonDown" Grid.Row="1" Foreground="White" Margin="10,0,0,0" FontSize="24" VerticalAlignment="Center"></TextBlock>

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

Storyboard.SetTarget(stringAnimationUsingKeyFrames, txt); //<--
Storyboard.SetTargetProperty(stringAnimationUsingKeyFrames, new PropertyPath(TextBlock.TextProperty));
story.Children.Add(stringAnimationUsingKeyFrames);
story.Begin(txt);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM