【问题标题】:Cannot animate 'Foreground.Color' on an immutable object instance无法在不可变对象实例上为“Foreground.Color”设置动画
【发布时间】:2016-10-18 17:21:57
【问题描述】:

无法为不可变对象实例上的“Foreground.Color”设置动画。

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

我不确定如何将动态动画添加到动态控件。

【问题讨论】:

  • 在为前景色设置动画之前,您应该为 Run 分配一个(可变的)画笔,例如 newLetter.Foreground = new SolidColorBrush(Colors.Red);
  • 谢谢,这是正确的。我以为它的默认颜色是黑色
  • 您有默认的黑色,但是(如错误消息所述)Brush 不可变。

标签: c# wpf


【解决方案1】:

为了具有动画效果,Run 的 Foreground Brush 必须是可变的,默认值不是。

您应该在制作动画之前指定一个新的 SolidColorBrush:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 2010-12-04
    相关资源
    最近更新 更多