我是 C# 的一个极端新手,但我一直在慢慢地阅读 Head Start C# 教程书(到目前为止发现它非常有趣)。但是,我在第一个“实验室”任务中遇到了困难:他们提供了用于控制 PictureBox 的代码,我可以让该代码在主窗体上工作,但我不能让它在一个类中工作. 我已经复习了旧课程,并且对我所缺少的东西有了一个很好的了解,但是对于我的生活,我无法弄清楚如何从课堂上访问主窗体的图片框(正如教程告诉我应该做的那样)。
这有点令人沮丧,因为我根本没有在书中跳到前面,但我发誓我们还没有涵盖这个。无论如何,吸引真正的程序员。
这是教程中提供的代码,位于名为“您的对象可以控制表单上的内容”的部分中(对于任何有本书的人来说,p208)。
Point p = MyPictureBox.Location
p.x += distance;
MyPictureBox.Location = p
下面我在下面发布我的代码的相关(我认为?)部分。Button1 在编译时为我工作,Button2 “工作”,因为当前类只是告诉它打印传递的 INT,因为我已经注释掉了我无法工作的代码。
提前致谢!
Form1 的代码:
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
// Namespaces I'll need.
namespace Troubleshooting_PicBoxes
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent(); // Start all the Form1 stuff (all IDE-generated)
}
private void button1_Click(object sender, EventArgs e) //method from clicking the first button
{
int distance = 5; // Create this variable called "distance"
Point BoxMovement = MyPictureBox.Location; //create a point called BoxMovement
BoxMovement.X += distance; // Adjust the X of BoxMovement by my distance int.
MyPictureBox.Location = BoxMovement; // now adjust the Box by the Point's location.
}
private void button2_Click(object sender, EventArgs e)
{
PicMover PicMoverObject1 = new PicMover(); // Reserve Space for&Create object
PicMoverObject1.MoveThatPic(5); // Execute Object Method with a value of 5
}
}
}
PicMover 类的代码:
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Troubleshooting_PicBoxes
{
class PicMover
{
public void MoveThatPic(int distance) // New method,
// takes a variable called Distance.
{
MessageBox.Show(distance.ToString()); // Just show us that Variable.
// I need to be able to access Form1's picture box before I can use this. :(
/* Point BoxMovement = MyPictureBox.Location; //create a point called BoxMovement
BoxMovement.X += distance; // Adjust the X of that by distance.
MyPictureBox.Location = BoxMovement; // now adjust the Box by the Point's location.
*/
}
}
}