I would like to create progra开发者_C百科mmatically an animation for the background color of a label but I have some problems.
I have implemented the following code:
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
but nothing happens!
The background is simply colored MidnightBlue and no animation.
Do you have any suggestions?
The problem I ran into last night (see here) was that using Storyboard.SetTarget
only works when the property you're animating is a property of a FrameworkElement
or FrameworkContentElement
.
You're not actually animating Label.Background
, you're animating SolidColorBrush.Color
. So (at least, as I understand it) you must create a name scope, give your brush a name, and use Storyboard.SetTargetName
to set it as a target.
This method works in C#; translating it to VB should be straightforward:
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);
}
I've seen exactly the same problem earlier today. But it was about render transfrom and in C#.
The short answer is to pass label as a target of animation, and change property path to (Label.Background).(SolidColorBrush.Color)
. The long answer involves playing with name scopes.
Hope this helps.
Cheers, Anvaka.
精彩评论