WPF中經過代碼設置控件的座標

用WPF作貪吃蛇小遊戲時,發現了一個問題:canvas

貪吃蛇的移動,我是經過不斷刷新Rectangle來實現(貪吃蛇的身體由一組Rectangle組成),所以須要不斷調整Rectangle的座標,可是WPF中沒有Location的相關設置windows

在網上查到能夠用Thickness實現app

Rectangle Rec = new Rectangle();
Rec.Margin = new Thickness(1, 2, 3, 4);

但老是調不許spa

其實能夠經過Canvas實現code

Canvas介紹blog

用代碼實現Canvas:遊戲

// Create the application's main window
mainWindow = new Window ();
mainWindow.Title = "Canvas Sample";

// Create the Canvas
myParentCanvas = new Canvas();
myParentCanvas.Width = 400;
myParentCanvas.Height = 400;

// Define child Canvas elements
myCanvas1 = new Canvas();
myCanvas1.Background = Brushes.Red;
myCanvas1.Height = 100;
myCanvas1.Width = 100;
Canvas.SetTop(myCanvas1, 0);
Canvas.SetLeft(myCanvas1, 0);

myCanvas2 = new Canvas();
myCanvas2.Background = Brushes.Green;
myCanvas2.Height = 100;
myCanvas2.Width = 100;
Canvas.SetTop(myCanvas2, 100);
Canvas.SetLeft(myCanvas2, 100);

myCanvas3 = new Canvas();
myCanvas3.Background = Brushes.Blue;
myCanvas3.Height = 100;
myCanvas3.Width = 100;
Canvas.SetTop(myCanvas3, 50);
Canvas.SetLeft(myCanvas3, 50);

// Add child elements to the Canvas' Children collection
myParentCanvas.Children.Add(myCanvas1);
myParentCanvas.Children.Add(myCanvas2);
myParentCanvas.Children.Add(myCanvas3);

// Add the parent Canvas as the Content of the Window Object
mainWindow.Content = myParentCanvas;
mainWindow.Show ();

固然也能夠經過添加Canvas控件來實現。element

 

設置控件位置的方法:get

var posX = 10;
var posY = 10;
Rectangle Rec = new Rectangle(); Canvas.SetLeft(Rec, posX); Canvas.SetTop(Rec, posY); 你添加的canvas名字.Children.Add(Rec);
相關文章
相關標籤/搜索