路径绘图和数据绑定

时间:2011-01-07 23:30:43

标签: wpf xaml data-binding path

我正在寻找一种能够使用wpf Path元素绘制路径的方法,该路径将代表地图上的路线。我有Route类包含一组顶点,并希望用它来绑定。我真的不知道怎么开始.. 任何提示?

2 个答案:

答案 0 :(得分:24)

绑定所需要的主要功能是转换器将您的点转换为Geometry,路径将需要Data,这是我System.Windows.Point的单向转换器1}} - 数组到几何看起来像:

[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
}

现在真正剩下的就是创建它的一个实例并将其用作绑定的转换器。它在XAML中可能是什么样的:

<Grid>
    <Grid.Resources>
        <local:PointsToPathConverter x:Key="PointsToPathConverter"/>
    </Grid.Resources>
    <Path Data="{Binding ElementName=Window, Path=Points, Converter={StaticResource ResourceKey=PointsToPathConverter}}"
          Stroke="Black"/>
</Grid>

如果您需要绑定自动更新,您应该使用依赖项属性或接口,例如INotifyPropertyChanged / INotifyCollectionChanged

希望有所帮助:D

答案 1 :(得分:1)

你也可以这样试试:

public static class PathStrings
{
    public const string Add = "F1 M 22,12L 26,12L 26,22L 36,22L 36,26L 26,26L 26,36L 22,36L 22,26L 12,26L 12,22L 22,22L 22,12 Z";
}

然后在资源中创建一个PathString

<Window.Resources>
    <yourNamespace:PathStrings x:Key="pathStrings"/>
</Window.Resources>

然后以这种方式绑定它:

<Path Stroke="Black" Fill="Black" 
      Data="{Binding Source={StaticResource pathStrings}, Path=Add}"></Path>