wpf - 路径绘制和数据绑定(bind)

标签 wpf xaml data-binding path

我正在寻找一种能够使用 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/

相关文章:

c# - 从枚举值列表创建可检查上下文菜单的通用方法

c# - 如何将样式放在单独的 .xaml 文件中

wpf - 动态改变 FocusManager.FocusedElement

wpf - 如何创建自动滚动文本框

c# - 在 WPF 中创建 UI 设置的正确方法是什么?

css - 单击 DIV 应用动态数据绑定(bind)以使用 HTML 输入编辑 CSS - knockout.js

wpf - 如何在 WPF ItemsControl 中保留项目的排序顺序?

.net - 一个 110 kb 的 .NET 4.0 应用程序需要 10 秒的冷启动时间,这是 Not Acceptable !

xaml - 自动检测 TextBlock 中的 URL、电话号码、电子邮件

javascript - 通过 ng-model 更新不同的 $scope 对象属性