Control.Location.Y未返回正确位置

问题描述:

我是c#的新手。我正在尝试制作如下图所示的蓝色区域列表: enter image description hereControl.Location.Y未返回正确位置

我已经使用了简单的面板而不是列表框,因为我需要为每个条目添加控件。现在,您在图像中看到的列表是我为了测试其硬编码值而做的。但是现在,当我试图让每个条目在最后一个条目下动态移动时,我无法实现它。我已经使用了Control.Location.Y,但它每次返回第二个条目的Y坐标,并且条目彼此重叠。

下面是代码:

public void enterItems (listingPanel list, int loc) 
    { 
     items.Add(list); 
     int lastIndex = items.Count - 1; 
     int newLoc = items[lastIndex].Location.Y + 52; 
     this.Controls.Add(items[lastIndex]); 
     if (lastIndex >= 1) 
      items[lastIndex].Location = new Point(0, newLoc); 
     Console.WriteLine("index: " + lastIndex + ", location Y: " + (items[lastIndex].Location.Y + 52) + " last loc: " + items[lastIndex].Location.Y + "Total: " + items.Count); 
    } 

这是),其被调用enterItems为addItems(INT)的定义(方法:

private void addItems(int loc) 
    { 
     listingPanel lists = new listingPanel("Shashlik", Convert.ToString(20), Convert.ToString(2)); 
     listing.enterItems(lists, loc); 
    } 

这是调用为addItems事件(int)方法:

private void sellBtn_Click(object sender, EventArgs e) 
    { 
     //for (int i = 0; i<1000; i = i+52) 
      addItems(0); 
    } 

感谢提前:)

首先您将一个项目添加到列表中,然后您想将其相对于以前的项目进行定位。

但是因为你添加项目清单后,获得的最后一项的指标,实际上是相对于项目的定位到本身

请注意:如果你试图通过把int lastIndex = items.Count - 1来解决该问题之前添加的项目,它当然会抛出异常,因为lastIndex == -1,所以你必须提供一些第一项Y位置另一种方式。

+0

非常感谢您指出问题!我接下来做的只是在if条件中从lastIndex中减去1。 (lastIndex> = 1){items [lastIndex] .Location = new Point(0,items [lastIndex-1] .Location.Y + 52);} ; – user2978059