隐藏受影响的控件时WPF故事板动画是否继续运行?

问题描述 投票:4回答:2

我正在通过将RecokeDashOffset动画应用于Rectangle控件来实现“行军蚁”样式的动画。我希望动画在可见矩形时播放,但在隐藏矩形时不占用额外的CPU周期。 WPF是否足够聪明,可以在隐藏受影响的控件时自动暂停动画?

c# wpf animation visibility storyboard
2个回答
6
投票

没有WPF很聪明,可以not这样做:)。其背后的原因是动画系统无法对动画属性的功能做出假设(它可以是任何依赖项属性,与控件外观无关,在这种情况下,无论可见性如何,您都希望动画能够工作)。

您可以如下测试:

XAML:

<Window x:Class="WpfApplication1.TestBrowser"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="Animation Test"
        Height="300"
        Width="300">
    <StackPanel>
            <Button Content="Toggle label" 
                            Click="ToggleLableClick"/>
            <local:MyLabel x:Name="lbl" Content="Hello" />
    </StackPanel>
</Window>

C#:

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Animation;

namespace WpfApplication1
{
  public partial class TestBrowser : Window
  {
    public TestBrowser()
    {
      InitializeComponent();
        var da = new DoubleAnimation(0, 10, new Duration(TimeSpan.FromSeconds(10)))
                    {
                        AutoReverse = true,
                        RepeatBehavior = RepeatBehavior.Forever
                    };
        lbl.BeginAnimation(MyLabel.DoublePropertyProperty, da);
    }

    private void ToggleLableClick(object sender, RoutedEventArgs e)
    {
        lbl.Visibility = lbl.IsVisible ? Visibility.Collapsed : Visibility.Visible;
    }
  }

    public class MyLabel : Label
    {
        public double DoubleProperty
        {
            get { return (double)GetValue(DoublePropertyProperty); }
            set { SetValue(DoublePropertyProperty, value); }
        }

        public static readonly DependencyProperty DoublePropertyProperty =
                DependencyProperty.Register("DoubleProperty", typeof(double), typeof(MyLabel), 
                new FrameworkPropertyMetadata(0.0,
                    FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange, OnDoublePropertyChanged));

        private static void OnDoublePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            Trace.WriteLine(e.NewValue);
        }

        protected override Size MeasureOverride(Size constraint)
        {
            Trace.WriteLine("Measure");
            return base.MeasureOverride(constraint);
        }

        protected override Size ArrangeOverride(Size arrangeBounds)
        {
            Trace.WriteLine("Arrange");
            return base.ArrangeOverride(arrangeBounds);
        }
    }
}

您将在调试输出中看到WPF的出色表现:无论控件是否可见,它都显示DoubleProperty发生了变化,但是对于度量/排列,可见性很重要。折叠控件时不会调用处理程序,即使我将DoubleProperty标记为会影响度量和排列的属性...


0
投票

我认为动画会继续,但是渲染系统会意识到矩形是​​不可见的,不会浪费时间重新绘制任何东西。

可以设置“可见性”或“不透明度”属性的动画,如果动画系统考虑到可见性,则该动画将不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.