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 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控件来实现。

 

设置控件位置的方法:

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

 

转载于:https://www.cnblogs.com/AraragiTsukihi/p/5845205.html

你可能感兴趣的:(WPF中通过代码设置控件的坐标)