3

这是一个动画形状Y2属性的简单程序。Line请注意,我使用该SetTarget方法来定位Line. 该程序运行良好。

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

namespace SoGeneratingAnimatedLine
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var canvas = new Canvas();

            Content = canvas;

            var sb = new Storyboard();

            var line = new Line()
            {
                X1 = 10, Y1 = 10,
                X2 = 90, Y2 = 10,
                Stroke = Brushes.Black,
                StrokeThickness = 2
            };

            canvas.Children.Add(line);

            var animation = new DoubleAnimation(10, 90, new Duration(TimeSpan.FromMilliseconds(1000)));

            sb.Children.Add(animation);

            Storyboard.SetTarget(animation, line);
            Storyboard.SetTargetProperty(animation, new PropertyPath(Line.Y2Property));

            MouseDown += (s, e) => sb.Begin(this);
        }
    }
}

这是一个类似的程序,它对 a 的 a 进行动画处理EndPointLineGeometry它是Datafor a Path

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

namespace SoGeneratingAnimatedLine
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            var canvas = new Canvas();

            Content = canvas;

            var sb = new Storyboard();

            var lineGeometry = 
                new LineGeometry(new Point(10, 10), new Point(90, 10));

            var path = new Path()
            {
                Stroke = Brushes.Black,
                StrokeThickness = 2,
                Data = lineGeometry
            };

            canvas.Children.Add(path);

            var animation =
                new PointAnimation(
                    new Point(90, 10),
                    new Point(90, 90),
                    new Duration(TimeSpan.FromMilliseconds(1000)));

            sb.Children.Add(animation);

            Storyboard.SetTarget(animation, lineGeometry);
            Storyboard.SetTargetProperty(animation, new PropertyPath(LineGeometry.EndPointProperty));

            MouseDown += (s, e) => sb.Begin(this);
        }
    }
}

这第二个版本不起作用。但是,如果我替换该行:

Storyboard.SetTarget(animation, lineGeometry);

和:

RegisterName("geometry", lineGeometry);
Storyboard.SetTargetName(animation, "geometry");

然后动画运行。

为什么SetTarget第二个程序的版本不起作用?什么时候可以SetTarget代替RegisterName/SetTargetName组合使用?这两种方法有什么区别?

4

2 回答 2

1

根本不需要故事板。只需直接在 LineGeometry 上调用BeginAnimation :

lineGeometry.BeginAnimation(LineGeometry.EndPointProperty, animation);
于 2012-11-04T12:28:16.990 回答
0

调用 RegisterName 是必要的,以便在代码中创建应用程序时正确连接动画故事板。这是因为故事板的关键属性之一TargetName使用运行时名称查找,而不是能够获取对目标元素的引用。即使可以通过代码引用访问该元素也是如此。

于 2019-07-15T13:17:40.110 回答