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

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

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

在网上查到可以用Thickness实现

Rectangle Rec = new Rectangle();
Rec.Margin = new Thickness(, , , );

但总是调不准

其实可以通过Canvas实现

Canvas介绍

用代码实现Canvas:

// Create the application's main window
mainWindow = new Window ();
mainWindow.Title = "Canvas Sample"; // Create the Canvas
myParentCanvas = new Canvas();
myParentCanvas.Width = ;
myParentCanvas.Height = ; // Define child Canvas elements
myCanvas1 = new Canvas();
myCanvas1.Background = Brushes.Red;
myCanvas1.Height = ;
myCanvas1.Width = ;
Canvas.SetTop(myCanvas1, );
Canvas.SetLeft(myCanvas1, ); myCanvas2 = new Canvas();
myCanvas2.Background = Brushes.Green;
myCanvas2.Height = ;
myCanvas2.Width = ;
Canvas.SetTop(myCanvas2, );
Canvas.SetLeft(myCanvas2, ); myCanvas3 = new Canvas();
myCanvas3.Background = Brushes.Blue;
myCanvas3.Height = ;
myCanvas3.Width = ;
Canvas.SetTop(myCanvas3, );
Canvas.SetLeft(myCanvas3, ); // 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);
上一篇:android中设置控件获得焦点


下一篇:Python字符串类型格式化之format方法