代码之家  ›  专栏  ›  技术社区  ›  Drake

使用WPF在运行时为背景动画添加标签

  •  0
  • Drake  · 技术社区  · 14 年前

    我想以编程方式为标签的背景色创建动画,但我有一些问题。

      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
    

    但什么也没发生 !

    背景颜色仅为午夜蓝色,没有动画。

    2 回复  |  直到 14 年前
        1
  •  2
  •   Community datashaman    7 年前

    我昨晚遇到的问题(参见 here Storyboard.SetTarget 仅当正在设置动画的属性是 FrameworkElement FrameworkContentElement

    你不是真的在做动画 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);
    }
    
        2
  •  0
  •   Community datashaman    7 年前

    我确实见过 the same problem 今天早些时候。但它是关于渲染转换和C#。

    简单的答案是将标签作为动画的目标传递,并将特性路径更改为 (Label.Background).(SolidColorBrush.Color) . The long answer 涉及使用名称作用域。

    希望这有帮助。