如何在Silverlight中绘制线条指定高度

本文关键字:高度 绘制 Silverlight | 更新日期: 2023-09-27 18:27:50

我正在尝试在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);

感谢

如何在Silverlight中绘制线条指定高度

是的,行的格式是:

<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);

不能,必须指定X1X2Y1Y2。但是你可以创建辅助方法来帮助你:

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.TopCanvas.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,当设置在GridStackPanel或其他容器中时,线条将无法正确绘制。你可以利用它的Margin,我认为这会有所帮助。但是,除非有特定的原因,否则需要使用Canvas定位,我建议您坚持使用第一种方法,并明确指定两个坐标。