【问题标题】:Label background animation at runtime with WPF使用 WPF 在运行时标记背景动画
【发布时间】:2018-07-27 11:42:40
【问题描述】:

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

我已经实现了以下代码:

  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,没有动画。

你有什么建议吗?

【问题讨论】:

    标签: wpf vb.net animation


    【解决方案1】:

    我昨晚遇到的问题(请参阅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);
    }
    

    【讨论】:

      【解决方案2】:

      我今天早些时候完全看到了the same problem。但它是关于渲染转换和 C# 的。

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

      希望这会有所帮助。

      干杯,安瓦卡。

      【讨论】:

      • 感谢您的回答,我尝试按照您的建议更改路径,但出现异常:无法解析属性路径中的所有属性引用 '(Label.Background).(SolidColorBrush.Color) '。验证适用的对象是否支持这些属性。
      • 您是否也更改了情节提要目标?
      猜你喜欢
      • 1970-01-01
      • 2012-12-18
      • 1970-01-01
      • 1970-01-01
      • 2014-12-25
      • 1970-01-01
      • 2016-04-21
      • 1970-01-01
      • 2013-12-09
      相关资源
      最近更新 更多