将XAML PathGeometry转换为WPF PathGeometry

3
我希望得到一个由LineSegment组成的PathGeometry。
因此,我使用了以下第一段代码,但是出现了错误。
PathGeometry temp = (PathGeometry)Geometry.Parse(
            "<PathGeometry.Figures>" +
                "<PathFigure StartPoint=\"193.5,283.5\" IsClosed=\"True\">" +
                    "<PathFigure.Segments>" +
                        "<LineSegment Point=\"418.5,283.5\" />" +
                        "<LineSegment Point=\"418.5,508.5\" />" +
                        "<LineSegment Point=\"193.5,508.5\" />" +
                        "<LineSegment Point=\"193.5,283.5\" />" +
                    "</PathFigure.Segments>" +
                "</PathFigure>" +
            "</PathGeometry.Figures>");

如果我使用第二个代码,虽然不会出现错误,但它并不包含LineSegment。结果将是PolyLineSegment,但我想要的是LineSegment。

PathGeometry temp = (PathGeometry)Geometry.Parse(
                "M29,329L30,331L31,334L33,336L34,338L36,341L38,343L39,345L41,348L44,352L46,353L47,355L48,356L49,357L49,357L50,358L50,358L51,357L50,356L51,354L51,350L53,342L54,334L58,320L60,315L61,311L63,308L63,306L64,304L65,303L65,302L66,301L66,301L66,301L66,301L66,301L66,301L66,301");

我该如何将XAML PathGeometry转换为WPF PathGeometry?

谢谢。

1个回答

9

您用于解析XAML的代码有误,您需要使用XAML读取器并将结果转换为所需类型。例如:

System.Windows.Shapes.Path newPath = (System.Windows.Shapes.Path)System.Windows.Markup.XamlReader.Parse("<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'  Width='20' Height='80' Stretch='Fill' Fill='#FF000000' Data='M 20,25.2941L 20,29.4118L 15.9091,29.4118L 15.9091,40L 12.2727,40L 12.2727,29.4118L 2.54313e-006,29.4118L 2.54313e-006,25.6985L 13.4872,7.62939e-006L 15.9091,7.62939e-006L 15.9091,25.2941L 20,25.2941 Z M 12.2727,25.2941L 12.2727,5.28493L 2.09517,25.2941L 12.2727,25.2941 Z M 20,65.2941L 20,69.4118L 15.9091,69.4118L 15.9091,80L 12.2727,80L 12.2727,69.4118L -5.08626e-006,69.4118L -5.08626e-006,65.6985L 13.4872,40L 15.9091,40L 15.9091,65.2941L 20,65.2941 Z M 12.2727,65.2941L 12.2727,45.2849L 2.09517,65.2941L 12.2727,65.2941 Z ' HorizontalAlignment='Left' VerticalAlignment='Top' Margin='140,60,0,0'/>");
LayoutRoot.Children.Add(newPath);

如果您正在使用代码后端,那么您想解析XAML片段的原因是什么?您可以按照以下方式以编程方式创建路径:
Path path = new Path();
PathGeometry geometry = new PathGeometry();
PathFigure figure = new PathFigure();
figure.StartPoint = new Point(10,10); 
figure.Segments.Add(new LineSegment()
{
  Point = new Point (20, 20)
});

// e.g. add more segments here

geometry.Figures.Add(figure);
path.Data = geometry;

一条路径由几何图形组成,几何图形则由图形组成,而图形则是由线段组成的!
如果您想在代码后端使用简化的路径数据,可以使用通用值转换器:

http://www.scottlogic.co.uk/blog/colin/2010/07/a-universal-value-converter-for-wpf/


因为我想将PathGeometry保存到XAML文件中,并从XAML文件中恢复PathGeometry。 - Hong Lim
路径(Path)、路径几何(PathGeometry)和路径图形(PathFigure)的代码对我非常有帮助,谢谢。 - Mike Malter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接