2015-03-31 71 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); 
     } 
    }