2015-03-31 78 views
0

我试图将我的项目从WinForms移动到WPF,但我无法在此成功。我有一个图片框,一个接一个的线条,我可以在一个循环中使用DrawLine(笔,点,点)。但是,当我试图通过使用WPF来做到这一点,我不能menage。绘制线阵列WPF

这是代码片段,我已经在使用的WinForms:

for (x = 0; x < X_COORD_END - X_COORD_START; x += 1) 
{ 
       System.Drawing.Point point1 = new System.Drawing.Point(x, 30); 
       System.Drawing.Point point2 = new System.Drawing.Point(x, 60); 
       e.Graphics.DrawLine(myPen, point1, point2); 
} 

,结果是:enter image description here

我试图用线阵列上WPF,但我给了一个错误在canvas.Children.Add线。现在我正尝试使用积分,但是我无法按照自己的意愿安排积分。这是我已经尝试过:

private void DrawLine(Point[] points) 
    { 
     Polyline line = new Polyline(); 
     PointCollection collection = new PointCollection(); 
     foreach (Point p in points) 
     { 
      collection.Add(p); 
     } 
     line.Points = collection; 
     line.Stroke = new SolidColorBrush(Colors.Black); 
     line.StrokeThickness = 20; 
     scanCanvas.Children.Add(line); 
    } 


    for (int counter = 0; counter < 1000; counter++) 
     { 
      points[counter] = new Point(counter, 30); 
     } 

     DrawLine(points); 

回答

1

使用Stackpanel为您的方案。我使用了一个线阵列,这与你在winforms中完成的事情类似。

MainWindow.xaml

<Window x:Class="SO.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="350" Width="525"> 
<StackPanel x:Name="stackGraphicsArea" Orientation="Horizontal"/> 
</Window> 

MainWindow.xaml.cs

public partial class MainWindow : Window 
    { 
    public MainWindow() 
      { 
       InitializeComponent(); 
       Line[] lines = new Line[1000]; 
       for(int i=0; i<1000;i++) 
       { 
        lines[i] = new Line(); 
        lines[i].Stroke = new SolidColorBrush(Colors.Red); 
        lines[i].StrokeThickness = 5; 
        lines[i].X1 = 0; 
        lines[i].X2 = 0; 
        lines[i].Y1 = 30; 
        lines[i].Y2 = 20; 
       } 
       DrawLines(lines); 
      } 

    private void DrawLines(Line[] _lines) 
      { 
       foreach (Line _line in _lines) 
       { 
        stackGraphicsArea.Children.Add(_line); 
       } 
      } 
} 
+0

嘿,感谢您的解决方案斯里曼。由于我真的是WPF的新手,我从来没有听说过Stackpanel,所以我想我以另一种方式做了我想做的事情。 – 2015-03-31 13:13:32

0

斯里曼雷迪已经回答了我的问题,但我想我应该张贴自己的解决方案过于:

private void DrawLine(int x_coord_start, int y_coord_start, int x_coord_end, int thickness, Color color) 
    { 
     Random rand = new Random(); 
     for (int x = 0; x < x_coord_end - x_coord_start; x++) 
     { 
      double newTop = rand.Next(); 

      Line top = new Line(); 
      top.Stroke = new SolidColorBrush(color); 
      top.StrokeThickness = x + 1; 

      top.X1 = x_coord_start + x; 
      top.Y1 = y_coord_start; 
      top.X2 = x_coord_start + x; 
      top.Y2 = y_coord_start + thickness; 

      Canvas.SetTop(top, 0); 
      Canvas.SetLeft(top, 0 /*x * top.Width*/); 
      scanCanvas.Children.Add(top); 
     } 
    }