[英]Does a WPF storyboard animation continue to run when the affected control is hidden?
我正在通过将 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
变化,但是当涉及到 Measure/Arrange 时,可见性很重要。 控件折叠时不会调用处理程序,即使我将DoubleProperty
标记为影响测量和排列的属性...
我认为动画继续,但渲染系统会意识到矩形是不可见的,不会浪费时间重新绘制任何东西。
可以为 Visibility 或 Opacity 属性设置动画,如果动画系统考虑了可见性,这将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.