Here's a simple program which animates the Y2
property of a Line
shape. Note that I use the SetTarget
method to target the Line
. This program works fine.
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);
}
}
}
Here's a similar program which animates the EndPoint
of a LineGeometry
which is the Data
for 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);
}
}
}
This second version does not work. However, if I replace the line:
Storyboard.SetTarget(animation, lineGeometry);
with:
RegisterName("geometry", lineGeometry);
Storyboard.SetTargetName(animation, "geometry");
then the animation runs.
Why doesn't the SetTarget
version of the second program work? When is it OK to use SetTarget
instead of the RegisterName
/SetTargetName
combo? What's the difference in the two approaches?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…