我正在尝试使用数据绑定在WPF中制作动画。我正在使用MatrixAnimationUsingPath让形状沿着路径移动。路径在我的viewModel中表示为一个数组;Point[]。如何将我的点属性绑定到我的viwmodel,以便我可以将其与MatrixAnimationUsingPath一起使用。
<Storyboard>
<MatrixAnimationUsingPath Storyboard.TargetName="MyMatrixTransform"
Storyboard.TargetProperty="Matrix" DoesRotateWithTangent="True"
Duration="0:0:5" RepeatBehavior="Forever">
<MatrixAnimationUsingPath.PathGeometry>
<PathGeometry>
// WHAT TO PUT HERE!
</PathGeometry>
</MatrixAnimationUsingPath.PathGeometry>
</MatrixAnimationUsingPath>
</Storyboard>
我能够使用值转换器从这些点中创建路径,但是我无法在MatrixAnimationUsingPath中使用该路径。
<Path Name="MyPath" StrokeThickness="2" Data="{Binding Path=Points, Converter={StaticResource ResourceKey=PointsToPathConverter}}">
在评论之后添加:
我以前没怎么用过值转换器。我使用的转换器是在线找到的。我该如何修改它?
[ValueConversion(typeof(Point[]), typeof(Geometry))]
public class PointsToPathConverter : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
Point[] points = (Point[])value;
if (points.Length > 0)
{
Point start = points[0];
List<LineSegment> segments = new List<LineSegment>();
for (int i = 1; i < points.Length; i++)
{
segments.Add(new LineSegment(points[i], true));
}
PathFigure figure = new PathFigure(start, segments, false); //true if closed
PathGeometry geometry = new PathGeometry();
geometry.Figures.Add(figure);
return geometry;
}
else
{
return null;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
#endregion
}
Source
(或RelativeSource
或ElementName
)属性设置为具有Points
属性的对象。但是您应该在Visual Studio的输出窗口中看到绑定错误消息。 - ClemensSource=ViewModel
不会起作用。如果有视图模型资源且“ViewModel”是其键,则可能是Source={StaticResource ViewModel}
。但是,由于我不知道您的代码,因此无法确定。但是,您可以在 MSDN 上的 数据绑定概述 文章中了解数据绑定。 - Clemens