其他分享
首页 > 其他分享> > 隐藏受影响的控件时,WPF故事板动画是否继续运行?

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

作者:互联网

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

解决方法:

不.WPF足够聪明,不能这样做:).其背后的原因是您无法预测动画属性的功能(它可以是任何依赖项属性,与控件外观无关).

您可以进行以下测试.

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标记为会影响测量和排列的属性.

标签:animation,storyboard,visibility,wpf,c
来源: https://codeday.me/bug/20191024/1918750.html