路径绘图和数据绑定

kub*_*003 9 data-binding wpf xaml path

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

H.B*_*.B. 24

你需要绑定的主要内容是一个转换器,它将你的点转换成Geometry路径所需的点Data,这是我从System.Windows.Point-array到Geometry 的单向转换器的样子:

[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
}
Run Code Online (Sandbox Code Playgroud)

现在剩下的就是创建它的一个实例并将其用作绑定的转换器.它在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>
Run Code Online (Sandbox Code Playgroud)

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

Hope可以帮助:D