2011-12-10 97 views
0

我是在wpf中使用路徑的新手,我不知道如何將一段xaml代碼轉換爲C#代碼。有人可以幫助我嗎?我引用了xaml代碼,然後嘗試將其轉換。 C#代碼缺少什麼?我還想問的另一件事是,如果一個網格足以讓路徑出現在窗口中。將xaml轉換爲C#代碼

<Path Stroke="Black" StrokeThickness="1"> 
<Path.Data> 
<PathGeometry> 
    <PathGeometry.Figures> 
    <PathFigureCollection> 
     <PathFigure StartPoint="10,100"> 
     <PathFigure.Segments> 
      <PathSegmentCollection> 
      <QuadraticBezierSegment Point1="200,200" Point2="300,100" /> 
      </PathSegmentCollection> 
     </PathFigure.Segments> 
     </PathFigure> 
    </PathFigureCollection> 
    </PathGeometry.Figures> 
</PathGeometry> 

我的C#代碼:

Path myPath = new Path(); 
myPath.Stroke = Brushes.Black; 
myPath.StrokeThickness = 1 
PathGeometry myPathGeometry = new PathGeometry(); 
myPathGeometry.Figures = new PathFigureCollection(); 

PathFigure myPathFigure = new PathFigure(); 
myPathFigure.StartPoint = new Point(10, 100); 
myPathFigure.Segments = new PathSegmentCollection(); 
QuadraticBezierSegment theSegment = new QuadraticBezierSegment(); 
theSegment.Point1 = new Point(200, 200); 
theSegment.Point2 = new Point(100, 300); 
myPathFigure.Segments.Add(theSegment); 
myPathGeometry.Figures.Add(myPathFigure); 

回答

1

您必須添加下面的端線,

myPath.Data = myPathGeometry; 

你應該添加X:命名您<Grid><Grid x:Name='myGrid'>

並添加下一行,

myGrid.Children.Add(myPath); 
+0

謝謝,你明白了。我已經添加了數據,但我誤解了myGrid.Children.Add(myPath); – arjacsoh

0

你的C#代碼可能看起來很像WPF標記。只需將路徑添加到您想將其顯示在控制

var myPath = new Path 
{ 
    Stroke = Brushes.Black, 
    StrokeThickness = 1.0, 
    Data = new PathGeometry 
    { 
     Figures = new PathFigureCollection 
     { 
      new PathFigure 
      { 
       StartPoint = new Point(10, 100), 
       Segments = new PathSegmentCollection 
       { 
        new QuadraticBezierSegment 
        { 
         Point1 = new Point(200, 200), 
         Point2 = new Point(300, 100), 
        }, 
       }, 
      }, 
     }, 
    }, 
}; 
myGrid.Children.Add(myPath); 
+0

但是形狀不會出現在窗口中。我在xaml文件中只有一個。怎麼了?我應該在哪裏添加出現的路徑? – arjacsoh

+0

只需命名您的網格並添加路徑即可。 –