我是Windows窗体的新手。我正在尝试实例化公共类的对象,并在按下button1时调用方法drawBoard()
。方法drawBoard()
我想通过它设置pictureBox2的属性。但是代码没有用。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class gameBoard :Form1
{
public void drawBoard()
{
pictureBox2.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
}
}
private void button1_Click(object sender, EventArgs e)
{
gameBoard a = new gameBoard();
a.drawBoard();
}
}
还尝试以其他两种方式实现这一点:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
pictureBox2.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
pictureBox2.BackColor = Color.Transparent;
}
}
和
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
pictureBox2.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
}
}
两者都有效。代码运行时直接加载图像。并且当按钮1以第二方式按下时。我想知道如何在用户定义的类的方法中定义时调用pictureBox属性。
答案 0 :(得分:4)
如果仔细观察,那么gameBoard
被定义为Form1
内的嵌套类,它也继承自Form
控件,这没有意义。您可能希望将类定义在外部(可能在单独的文件中)
public class gameBoard
{
private PictureBox _box;
public gameBoard(PictureBox box)
{
_box = box;
}
public void drawBoard()
{
_box.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
_box.SizeMode = PictureBoxSizeMode.Zoom;
}
}