2012-01-18 130 views
4

我正在爲Windows Phone編碼Microsoft Visual Studio 2010 Express。我需要把點添加到Canvas,但我不能......添加到畫布

for (float x = x1; x < x2; x += dx) 
{ 
    Point poin = new Point(); 
    poin.X = x; 
    poin.Y = Math.Sin(x); 
    canvas1.Children.Add(poin); 
} 

工作室說:

錯誤2參數1:無法從「System.Windows.Point」轉換爲'System.Windows.UIElement'

我的問題是:如何將點添加到Canvas

+1

的'Point'類不代表視覺點,但只是一組,你可以使用座標定義**你的點應顯示在哪裏。 – 2012-01-18 14:29:30

回答

0

根據錯誤,Canvas控件的子項必須是System.Windows.UIElement類的衍生品:System.Windows.Point不是。要實現你正在做的事情,你最好在WPF中使用幾何。有關如何操作的文章,請參閱here

+0

可能是你可以顯示的例子怎麼加點,這裏我只看到怎麼加點線 – Anatoly 2012-01-18 14:28:43

+2

點只是一條線,只是很短。 – 2012-01-18 14:30:56

1

您使用的Point不是UIElement而是一個結構,請使用Line代替。

Line lne = new Line(); 
lne.X1 = 10; 
lne.X2 = 11; 
lne.Y1 = 10; 
lne.Y2 = 10; 
canvas1.Children.Add(lne); 

你的想法...

編輯
改變: lne.X2 = 10 lne.X2 = 11

+0

但我怎麼能把它放在?工作室說:元素已經是另一個元素的孩子。 – Anatoly 2012-01-18 14:39:13

+0

這是可能的,如果你會嘗試添加相同的行兩次, 請添加Line lne = new Line();在此之前不要阻止。 – Sonosar 2012-01-18 14:41:40

+0

奇怪但這不起作用:( – Anatoly 2012-01-18 14:52:18

2

從您的代碼段我假設你想繪製一條曲線。要做到這一點,你可以看看GraphicsPath。您可以將點用作座標,而不是繪製單個點,而是通過線連接。然後,在您的代碼中,您可以使用AddLine方法創建GraphicsPath。例如,這可以被繪製到位圖上。

編輯

樣品(未測試):

GraphicsPath p = new GraphicsPath(); 

for (float x = x1; x < x2; x += dx) 
{ 
    Point point = new Point(); 
    point.X = x; 
    point.Y = Math.Sin(x); 

    Point point2 = new Point(); 
    point2.X = x+dx; 
    point2.Y = Math.Sin(x+dx); 

    p.AddLine(point, point2); 
} 

graphics.DrawPath(p); 

另一種方法是使用WPF Path類,它會的工作大致相同,但它是一個真正的UI元素,你可以添加到Canvas的孩子。

編輯

人士指出,上面的代碼是Windows窗體代碼。嗯,這裏是你可以在WPF做什麼:

myPolygon = new Polygon(); 
myPolygon.Stroke = System.Windows.Media.Brushes.Black; 
myPolygon.Fill = System.Windows.Media.Brushes.LightSeaGreen; 
myPolygon.StrokeThickness = 2; 
myPolygon.HorizontalAlignment = HorizontalAlignment.Left; 
myPolygon.VerticalAlignment = VerticalAlignment.Center; 

PointCollection points = new PointCollection(); 
for (float x = x1; x < x2; x += dx) 
{ 
    Point p = new Point(x, Math.Sin(x)); 
    points.Add(p); 
} 

myPolygon.Points = points; 
canvas1.Children.Add(myPolygon); 
+0

Microsoft Visual Studio 2010 Express沒有System.Drawing.dll – Anatoly 2012-01-18 14:41:38

+1

這個想法很好,但是這是WinForms代碼 – 2012-01-18 14:43:06

+1

@Anatoly:這不是Visual Studio的問題System.Drawing是.NET Framework的一部分,VS 2010需要一段時間來異步加載你可以作爲參考添加的程序集,等一下,然後按名稱對列表進行排序 – 2012-01-18 14:58:42

0

嘗試添加橢圓

Ellipse myEllipse = new Ellipse(); 
SolidColorBrush mySolidColorBrush = new SolidColorBrush(); 
mySolidColorBrush.Color = Color.FromArgb(255, 255, 255, 0); 
myEllipse.Fill = mySolidColorBrush; 
myEllipse.StrokeThickness = 2; 
myEllipse.Stroke = Brushes.White; 
myEllipse.Width = 200; 
myEllipse.Height = 100; 
Canvas.SetTop(myEllipse,50); 
Canvas.SetLeft(myEllipse,80); 
myCanvas.Children.Add(myEllipse);