你不能,你必须指定X1
, X2
, Y1
, Y2
。但是您可以创建辅助方法来帮助您:
public Line CreateVerticalLine(Point startPoint, double height, double thickness)
{
Line line = new Line();
line.X1 = startPoint.X;
line.Y1 = startPoint.Y;
line.X2 = startPoint.X;
line.Y2 = startPoint.Y + height;
line.StrokeThickness = thickness;
return line;
}
如果您决定使用Canvas.Top
andCanvas.Left
属性,您可以从它的原点画一条线:
public Line CreateVerticalLine(Point startPoint, double height, double thickness)
{
Line line = new Line();
//technically, you don't need to specify 0 for these, but I'll leave them
//here to be explicit about what's going on
line.X1 = 0;
line.Y1 = 0;
line.X2 = 0;
line.Y2 = height;
Canvas.SetTop(line, startPoint.Y);
Canvas.SetLeft(line, startPoint.X);
line.StrokeThickness = thickness;
return line;
}
请注意,您可能希望使用Canvas.SetTop
和Canvas.SetLeft
便利方法,因为它们将是类型安全的并为您执行隐式类型转换。
另请注意,您可能需要重新考虑这一点。当设置在、或其他容器中时,通过利用Canvas.Top/Left
您的线将无法正确绘制。您可以改为利用它,我认为这会有所帮助。但除非有特定原因需要使用 Canvas 定位,否则我建议您坚持第一种方法并明确指定两个坐标。Grid
StackPanel
Margin