Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define the path data from code behind in silverlight

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" />
like image 490
Malcolm Avatar asked Aug 16 '10 12:08

Malcolm


3 Answers

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;
like image 101
Malcolm Avatar answered Oct 04 '22 21:10

Malcolm


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);
like image 42
Thomas Levesque Avatar answered Oct 04 '22 20:10

Thomas Levesque


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);
}
like image 38
Thomas Avatar answered Oct 04 '22 21:10

Thomas