Convert XAML PathGeometry to WPF PathGeometry

我们两清 提交于 2019-12-04 12:31:52

Your code for parsing the XAML is incorrect, you need to use a XAML reader and cast the result to the required type. e.g.:

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);

If you are using code-behind, is there any reason you want to parse a XAML snippet? You can programmatically create a path as follows:

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;

A path is composed of a geometry, which is composed of figures, which are composed of segments!

If you want to use the simplified path data in code behind you could use a universal value converter:

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!