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" />
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;
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);
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With