码迷,mamicode.com
首页 > Windows程序 > 详细

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

时间:2016-09-06 13:38:50      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:

用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控件来实现,添加之后

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

 

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

标签:

原文地址:http://www.cnblogs.com/AraragiTsukihi/p/5845205.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!