3

我正在尝试使用数据绑定在 WPF 中制作动画。我正在使用 MatrixAnimationUsingPath 让形状跟随路径。路径在我的 viewModel 中表示为一个数组;观点[]。如何在我的 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
}
4

2 回答 2

0

You are almost there ... you need a converter that return PathFigure instead of points.

If you Modify the converter the code should work.

Hope it helps.

于 2013-10-30T11:31:55.113 回答
0

未经测试:您应该能够像这样重用 Path.Data 绑定表达式:

<MatrixAnimationUsingPath ...
    PathGeometry="{Binding Path=Points,
                   Converter={StaticResource ResourceKey=PointsToPathConverter}}" />

但是,我不确定您是否可能需要显式设置绑定源对象,因为 MatrixAnimationUsingPath 对象没有 DataContext。

于 2013-10-30T11:38:44.397 回答