简体   繁体   中英

Cannot animate 'Foreground.Color' on an immutable object instance

Cannot animate 'Foreground.Color on an immutable object instance.

private void AnimColor()
    {
        int counter = 0;
        Storyboard mystoryboard = new Storyboard();
        foreach (char letter in txtSend.Text)
        {
            Run newLetter = new Run(letter.ToString());
            newLetter.Name = "letter_" + counter.ToString();
            textblock1.Inlines.Add(newLetter);
            counter++;
            ColorAnimation k = new ColorAnimation();
            //MessageBox.Show(letter.Name);
            Storyboard.SetTarget(k, newLetter);
            Storyboard.SetTargetProperty(k, new PropertyPath("Foreground.Color"));
            k.From = Colors.Red;
            k.To = Colors.Blue;
            k.Duration = TimeSpan.FromSeconds(0.5);
            k.BeginTime = TimeSpan.FromSeconds(0.5 * counter);
            mystoryboard.Children.Add(k);
        }
        try
        {
            mystoryboard.Begin(this);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

I'm not exactly sure how to add a dynamic animation to a dynamic control.

In order to be animatable, the Foreground Brush of the Run must be mutable, which the default value isn't.

You should assign a new SolidColorBrush before animating:

newLetter.Foreground = new SolidColorBrush(Colors.Black);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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