首页 > 代码库 > WPF中通过代码设置控件的坐标

WPF中通过代码设置控件的坐标

用WPF做贪吃蛇小游戏时,发现了一个问题:

贪吃蛇的移动,我是通过不断刷新Rectangle来实现(贪吃蛇的身体由一组Rectangle组成),因此需要不断调整Rectangle的坐标,但是WPF中没有Location的相关设置

在网上查到可以用Thickness实现

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

但总是调不准

其实可以通过Canvas实现

Canvas介绍

用代码实现Canvas:

// Create the application‘s main windowmainWindow = new Window ();mainWindow.Title = "Canvas Sample";// Create the CanvasmyParentCanvas = new Canvas();myParentCanvas.Width = 400;myParentCanvas.Height = 400;// Define child Canvas elementsmyCanvas1 = 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 collectionmyParentCanvas.Children.Add(myCanvas1);myParentCanvas.Children.Add(myCanvas2);myParentCanvas.Children.Add(myCanvas3);// Add the parent Canvas as the Content of the Window ObjectmainWindow.Content = myParentCanvas;mainWindow.Show ();

也可以通过添加Canvas控件来实现,添加之后

Rectangle Rec = new Rectangle();Canvas.SetLeft(Rec, posX);Canvas.SetTop(Rec, posY);你添加的canvas名字.Children.Add(Rec);

 

WPF中通过代码设置控件的坐标