System.Invalid.Operation.Exception - PullRequest
       1

System.Invalid.Operation.Exception

1 голос
/ 15 апреля 2019

Я пытаюсь поместить анимацию в программно сделанный текстовый блок на 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>

1 Ответ

1 голос
/ 15 апреля 2019

Используйте метод Storyboard.SetTarget вместо Storyboard.SetTargetName:

Storyboard.SetTarget(stringAnimationUsingKeyFrames, txt); //<--
Storyboard.SetTargetProperty(stringAnimationUsingKeyFrames, new PropertyPath(TextBlock.TextProperty));
story.Children.Add(stringAnimationUsingKeyFrames);
story.Begin(txt);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...