【问题标题】:'ColorAnimation' animation object cannot be used to animate property 'Background' because it is of incompatible type 'System.Windows.Media.Brush'“ColorAnimation”动画对象不能用于动画属性“背景”,因为它的类型不兼容“System.Windows.Media.Brush”
【发布时间】:2016-10-18 15:37:26
【问题描述】:

我正在尝试以编程方式使用 ColorAnimation 来为单元格设置动画,但是当我执行 storyboard.Begin() 时我得到了这个

'System.Windows.Media.Animation.ColorAnimation' animation object cannot be used to animate property 'Background' because it is of incompatible type 'System.Windows.Media.Brush'.

我已将我的ColorAnimation 定义为

var storyBoard = new  Storyboard();
ColorAnimation colorAnimation = new ColorAnimation
{
    From = Colors.Red,
    To = Colors.CornflowerBlue,
    Duration = TimeSpan.FromSeconds(1),
    FillBehavior = FillBehavior.Stop
};

关于它的使用情况

if (column.UniqueName != "_ID")
{
    var animation = animationMapping[column.UniqueName].Animation;
    var storyboard = animationMapping[column.UniqueName].Storyboard;

    Storyboard.SetTarget(animation, cell.Content as TextBlock);
    //Storyboard.SetTargetProperty(animation,
    //    new PropertyPath((TextBlock.Foreground).Color"));

    PropertyPath colorTargetPath = new PropertyPath(TextBlock.BackgroundProperty);
    Storyboard.SetTargetProperty(animation, colorTargetPath);

    storyboard.Begin();
}

我必须将什么参数传递给新的PropertyPath?我尝试关注this example,但没有任何运气。

【问题讨论】:

  • 使用这个PropertyPath colorTargetPath = new PropertyPath("(TextBlock.Background).(SolidColorBrush.Color)", null);
  • @AnjumSKhan 你真的试过你的代码吗?如果我运行你的代码,我会得到一个InvalidOperationException 和消息Cannot resolve all property references in the property path '(TextBlock.Background).(SolidColorBrush.Color)‌'. Verify that applicable objects support the properties.。所以很明显这段代码不起作用。 (请参阅我的工作答案。)

标签: c# wpf wpf-animation


【解决方案1】:

您必须为BrushColor 指定正确的PropertyPath

所以不是

PropertyPath colorTargetPath = new PropertyPath(TextBlock.BackgroundProperty);

你必须使用

PropertyPath colorTargetPath =
  new PropertyPath("(0).(1)", TextBlock.BackgroundProperty, SolidColorBrush.ColorProperty);

这相当于您链接答案的 XAML 中的 Storyboard.TargetProperty="(TextBlock.Background).Color"

现在它应该可以工作了——至少如果TextBlock.Background 的现有BrushSolidColorBrush。如果没有,您必须将PropertyPath 调整为您的Brush 类型。

【讨论】:

  • @haindl 我已经尝试过你的建议,但我得到的“背景”属性没有指向路径“(0).(1)”中的 DependencyObject。
  • @advapi 如果受影响的TextBlockBackgroundnull,则会收到此错误消息。 (nullTextBlock.Background 的默认值。)在开始 Storyboard 之前,请检查 Background 是否设置为 SolidColorBrush,因为您无法为不存在的东西设置动画。
猜你喜欢
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 2015-07-29
  • 2013-10-28
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多