Define the path data from code behind in silverlight

你离开我真会死。 提交于 2019-12-19 02:31:17

问题


I have the following below path data which is in xaml. I want to define the same path data from the code behind.

<Path  Data="M 250,40 L200,20 L200,60 Z" />

回答1:


From Codebehind :

Path orangePath = new Path();

        PathFigure pathFigure = new PathFigure();

        pathFigure.StartPoint = new Point(250, 40);

        LineSegment lineSegment1 = new LineSegment();
        lineSegment1.Point = new Point(200, 20);
        pathFigure.Segments.Add(lineSegment1);

        LineSegment lineSegment2 = new LineSegment();
        lineSegment2.Point = new Point(200, 60);
        pathFigure.Segments.Add(lineSegment2);

        PathGeometry pathGeometry = new PathGeometry();
        pathGeometry.Figures = new PathFigureCollection();

        pathGeometry.Figures.Add(pathFigure);

        orangePath.Data = pathGeometry;

Edit :

//we should have to set this true to draw the line from lineSegment2 to the start point

pathFigure.IsClosed = true;



回答2:


You need to use a TypeConverter:

Path path = new Path();
string sData = "M 250,40 L200,20 L200,60 Z";
var converter = TypeDescriptor.GetConverter(typeof(Geometry));
path.Data = (Geometry)converter.ConvertFrom(sData);



回答3:


Disclaimer: I've only done this with the Path as a DataTemplate as a listbox. Should work.

//of course the string could be passed in to a constructor, just going short route.
public class PathData
{
   public string Path { get { return "M 250,40 L200,20 L200,60 Z"; } }
}

void foo()
{
   var path = new Path() { Stroke = new SolidColorBrush(Colors.Black) };
   var data = new PathData();
   var binding = new Binding("Path") { Source=data, Mode=BindingMode.OneWay };
   path.SetBinding(Path.DataProperty, binding);
}


来源:https://stackoverflow.com/questions/3493163/define-the-path-data-from-code-behind-in-silverlight

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