我在xaml中有以下路径数据。我想从后面的代码中定义相同的路径数据。
<Path Data="M 250,40 L200,20 L200,60 Z" />
答案 0 :(得分:16)
来自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;
修改:
//我们必须将此设置为true才能将lineSegment2中的行绘制到起点
pathFigure.IsClosed = true;
答案 1 :(得分:12)
您需要使用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);
答案 2 :(得分:2)
免责声明:我只使用Path作为DataTemplate作为列表框。应该工作。
//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);
}