程序假设在panel1上绘制形状。 这是我的主要表单的代码:
namespace DrawShapes
{
public partial class Form1 : Form
{
List<Shape> myShapeList;
Shape shape;
public Form1()
{
InitializeComponent();
}
public void AddShape(Shape myshape)
{
myShapeList.Add(shape);
}
public List<Shape> MyShapeList
{
get { return myShapeList; }
}
private void Form1_Load(object sender, EventArgs e)
{
myShapeList = new List<Shape>();
shape = new Shape();
}
private void drawMeButton_Click(object sender, EventArgs e)
{
EditShape editShape = new EditShape();
editShape.Shape = shape;
if (editShape.ShowDialog() == DialogResult.OK)
{
this.shape = editShape.Shape;
myShapeList.Add(shape);
panel1.Invalidate();
}
editShape.Dispose();
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
int panelWidth = panel1.ClientRectangle.Width;
int panelHeight = panel1.ClientRectangle.Height;
Pen penLine = new Pen(Color.Blue, 1);
Graphics g = e.Graphics;
if (myShapeList != null)
{
foreach (Shape element in myShapeList)
{
label1.Text = element.Width.ToString();
g.DrawRectangle(penLine, element.XCordinates, element.XCordinates, 50, 50);
}
}
}
}
}
这是我的编辑形状对话框的代码
namespace DrawShapes
{
public partial class EditShape : Form
{
Shape shape = null;
public EditShape()
{
InitializeComponent();
}
public Shape Shape
{
get { return shape; }
set { shape = value; }
}
private void button1_Click(object sender, EventArgs e)
{
shape.Width = 50;
shape.Height = 50;
shape.XCordinates = int.Parse(textBox1.Text);
shape.YCordinates = int.Parse(textBox2.Text);
shape.Type = 0;
DialogResult = DialogResult.OK;
}
}
}
我在设置形状对象(从“编辑形状”表单)到myShapeList时遇到问题,由于某种原因,所有属性都设置为0。请帮忙。
答案 0 :(得分:1)
问题可能是您的AddShape
方法。您似乎每次都添加shape
而不是传递给方法的形状(myshape
)。
如果你这样做会怎么样?
public void AddShape(Shape myshape)
{
myShapeList.Add(myshape); // myshapeinstead of shape
}
答案 1 :(得分:0)
您似乎并未真正将形状添加到造型列表中。您正在接受myShape,然后尝试添加形状。这应该是一个智能感知错误。
public void AddShape(Shape myshape)
{
myShapeList.Add(shape);
}
编辑:没关系,它不会出现错误,因为你有一个名为shape的成员变量。你为所有东西得到零,因为它调用了形状的默认构造函数。
答案 2 :(得分:0)
最大的问题在于您对编辑表单的调用。您正在向列表添加相同的对象引用。因此,当您在编辑表单中修改引用时,您将添加到列表中的所有元素更改为最新调用中设置的输入
将您的代码更改为
private void drawMeButton_Click(object sender, EventArgs e)
{
using(EditShape editShape = new EditShape())
{
// Here, create a new instance of a Shape and edit it....
editShape.Shape = new Shape();
if (editShape.ShowDialog() == DialogResult.OK)
{
// Add the new instance to the list, not the same instance
// declared globally. (and, at this point, useless)
myShapeList.Add(editShape.Shape);
panel1.Invalidate();
}
// The using blocks makes this call superflous
// editShape.Dispose();
}
}
然后不清楚何时调用方法AddShape(Shape myshape),但很明显你在该方法中有拼写错误
答案 3 :(得分:0)
我发现了我的错误。我用错误的参数创建了新的事件处理程序。因此,从未通过我的对话框确定按钮传递的信息从未正确分配。愚蠢的错误。谢谢你们。