2010-02-26 55 views
0

我想以编程方式创建标签背景颜色的动画,但我遇到了一些问题。使用WPF在运行时标签背景动画

我已经实现了下面的代码:

Public Sub DoBackgroundAnimation(ByVal obj As Label) 

     If obj Is Nothing Then Return 

     Dim animatedBrush As New SolidColorBrush() 
     animatedBrush.Color = Colors.MidnightBlue 

     Dim highlightAnimation As New ColorAnimation() 
     highlightAnimation.[To] = Colors.Transparent 
     highlightAnimation.Duration = TimeSpan.FromSeconds(1) 
     Storyboard.SetTarget(highlightAnimation, animatedBrush) 
     Storyboard.SetTargetProperty(highlightAnimation, New PropertyPath(SolidColorBrush.ColorProperty)) 

     Dim story As New Storyboard 
     story.Children.Add(highlightAnimation) 

     obj.Background = animatedBrush 
     story.Begin(obj) 

    End Sub 

但没有任何反应

背景是简单的彩色MidnightBlue和没有动画。

你有什么建议吗?

回答

2

昨晚我遇到的问题(请参阅here)是使用Storyboard.SetTarget仅适用于您正在动画的属性为FrameworkElementFrameworkContentElement的属性。

实际上,您并非动画Label.Background,您正在动画SolidColorBrush.Color。所以(至少,据我了解),您必须创建一个名称范围,给您的画笔命名,并使用Storyboard.SetTargetName将其设置为目标。

此方法在C#中工作;将其转换成VB应该直截了当:

void AnimateLabel(Label label) 
{ 
    // Attaching the NameScope to the label makes sense if you're only animating 
    // things that belong to that label; this allows you to animate any number 
    // of labels simultaneously with this method without SetTargetName setting 
    // the wrong thing as the target. 
    NameScope.SetNameScope(label, new NameScope()); 
    label.Background = new SolidColorBrush(Colors.MidnightBlue); 
    label.RegisterName("Brush", label.Background); 

    ColorAnimation highlightAnimation = new ColorAnimation(); 
    highlightAnimation.To = Colors.Transparent; 
    highlightAnimation.Duration = TimeSpan.FromSeconds(1); 

    Storyboard.SetTargetName(highlightAnimation, "Brush"); 
    Storyboard.SetTargetProperty(highlightAnimation, new PropertyPath(SolidColorBrush.ColorProperty)); 

    Storyboard sb = new Storyboard(); 
    sb.Children.Add(highlightAnimation); 
    sb.Begin(label); 
} 
+0

谢谢你,太棒了 – Drake 2010-03-02 14:28:19

0

我今天早些时候刚刚看到the same problem。但它是关于渲染转换和在C#中。

简短的答案是将标签作为动画的目标,并将属性路径更改为(Label.Background).(SolidColorBrush.Color)The long answer涉及玩名称范围。

希望这会有所帮助。

干杯,Anvaka。

+0

感谢你回答,我想如你所说更改路径,但我得到的异常:无法解析的属性路径的所有属性引用“(Label.Background) (SolidColorBrush.Color)”。验证适用的对象是否支持这些属性。 – Drake 2010-02-26 16:31:56

+0

你是否也改变了故事板目标? – Anvaka 2010-02-26 17:45:39