如何将一个 Point[] 转换为 PathGeometry?

3

我正在尝试使用数据绑定在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
}
2个回答

0

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

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

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


我已经尝试了你说的方法,没有出现任何错误,但是动画没有发生。你最后一句话是什么意思?也许这就是问题所在。 - user2590683
将绑定的Source(或RelativeSourceElementName)属性设置为具有Points属性的对象。但是您应该在Visual Studio的输出窗口中看到绑定错误消息。 - Clemens
因为这个原因,它并没有产生任何区别。而且也没有出现错误! - user2590683
我猜 Source=ViewModel 不会起作用。如果有视图模型资源且“ViewModel”是其键,则可能是 Source={StaticResource ViewModel}。但是,由于我不知道您的代码,因此无法确定。但是,您可以在 MSDN 上的 数据绑定概述 文章中了解数据绑定。 - Clemens

0

你已经接近成功了...你需要一个返回PathFigure而不是点的转换器。

如果你修改转换器,代码应该可以工作。

希望能帮到你。


我之前没怎么用过值转换器。我使用的这个转换器是在网上找到的。我该如何修改它呢?请看上面添加的值转换器的代码。 - user2590683
我能否只返回“figure”,而不是“geometry”?因为那样不起作用。 - user2590683

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接