我正在寻找一种能够使用 wpf Path 元素来绘制代表 map 上路线的路径的方法。我有包含顶点集合的 Route 类,并希望将其用于绑定(bind)。我真的不知道如何开始.. 有什么提示吗?
最佳答案
绑定(bind)所需的主要内容是一个转换器,它将您的点转换为几何
,路径将需要它作为数据
,这是我的一个-从 System.Windows.Point
数组到几何的转换器的方式如下:
[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
}
现在剩下的就是创建它的实例并将其用作绑定(bind)的转换器。它在 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>
如果您需要自动更新绑定(bind),则应使用依赖项属性或接口(interface),例如 INotifyPropertyChanged
/INotifyCollectionChanged
希望有帮助:D
关于wpf - 路径绘制和数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4631231/