0

我试图在 Silverlight 中画线,指定 Canvas.Left、Canvas.Top、Width、Height 属性。但它没有得到显示。我在这里想念什么?我试图在不指定坐标的情况下画线。

  Point pt1 = new Point();
            pt1.X = 50;
            pt1.Y = 50;

            Line l = new Line();
            l.Height = 5;
            l.Width = 5;
            l.SetValue(Canvas.TopProperty, pt1.Y);
            l.SetValue(Canvas.LeftProperty, pt1.X);

  this.LayoutRoot.Children.Add(l);

谢谢

4

2 回答 2

2

是的,行有这种格式:

<Line X1="50" Y1="50" X2="200" Y2="200" Stroke="Red" StrokeThickness="4" />

复制自http://www.c-sharpcorner.com/uploadfile/mahesh/line-in-wpf/

Line redLine = new Line();
redLine.X1 = 50;
redLine.Y1 = 50;
redLine.X2 = 200;
redLine.Y2 = 200;

// Create a red Brush
SolidColorBrush redBrush = new SolidColorBrush();
redBrush.Color = Colors.Red;

// Set Line's width and color
redLine.StrokeThickness = 4;
redLine.Stroke = redBrush;

// Add line to the Grid.
LayoutRoot.Children.Add(redLine);
于 2013-08-14T13:57:53.990 回答
1

你不能,你必须指定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.TopandCanvas.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.SetTopCanvas.SetLeft便利方法,因为它们将是类型安全的并为您执行隐式类型转换。

另请注意,您可能需要重新考虑这一点。当设置在、或其他容器中时,通过利用Canvas.Top/Left您的线将无法正确绘制。您可以改为利用它,我认为这会有所帮助。但除非有特定原因需要使用 Canvas 定位,否则我建议您坚持第一种方法并明确指定两个坐标。GridStackPanelMargin

于 2013-08-14T13:58:50.760 回答