开发者

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  Da开发者_Python百科ta="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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜