【问题标题】:Path drawing and data binding路径绘制和数据绑定
【发布时间】:2011-06-05 14:21:26
【问题描述】:

我正在寻找一种能够使用 wpf Path 元素绘制代表地图上路线的路径的方法。我有一个包含顶点集合的 Route 类,并希望将其用于绑定。我什至不知道如何开始.. 有什么提示吗?

【问题讨论】:

    标签: wpf xaml data-binding path


    【解决方案1】:

    绑定所需的主要内容是一个转换器,它将您的点转换为Geometry,路径将需要为Data,这是我从System.Windows.Point-array 到的单向转换器几何形状如下:

    [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

    【讨论】:

    • 太棒了。我以前写过转换器,但不知何故我想不通。我正在考虑使用 DataTemplates 或样式或类似的东西,但这是一个很好的解决方案。谢谢。
    • @PortlandRunner:它只是Point[] 类型的属性,调试单个绑定不在此答案的范围内。
    • @PortlandRunner:那我不明白你在问什么,除了点数组还有什么好说的?
    • @H.B.不完全是,但无论如何都不要介意。我为我正在尝试做的事情找到了另一种解决方案。 - 已删除评论。
    【解决方案2】:

    你也可以这样试试:

    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>
    

    【讨论】:

    • 谢谢,过去 6 年我一直在为此苦苦挣扎 :)
    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 2018-05-24
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多