【发布时间】:2018-08-11 10:51:20
【问题描述】:
我在 Windows 窗体应用程序中遇到了所有者绘制的列表框的问题。 列表框充满了包含它们自己的 UserControl 的对象。每个项目的用户控件显示在列表框中。 这一切都有效,但是当我向上或向下滚动时,UserControls 出现了一点偏移。 一旦我点击它们,它们就会跳到正确的位置。
在图片中,您可以看到白色的 UserControl 向右移动了一点,向下移动了一点。
这是它们在滚动之前的样子。
列表中充满了这种类型的对象:
class Class1
{
public UserControl1 UC;
public string Text;
public Class1(UserControl1 uc, string text)
{
UC = uc;
Text = text;
}
}
这是控制列表的类:
class ListDrawer
{
public ListBox LB;
public int HeaderHeight = 25;
public ListDrawer(ListBox lb)
{
LB = lb;
LB.DrawMode = DrawMode.OwnerDrawVariable;
LB.DrawItem += LB_DrawItem;
LB.MeasureItem += LB_MeasureItem;
}
private void LB_MeasureItem(object sender, MeasureItemEventArgs e)
{
ListBox lst = sender as ListBox;
Class1 c = (Class1)lst.Items[e.Index];
e.ItemHeight = HeaderHeight;
e.ItemHeight = e.ItemHeight + c.UC.Height;
}
private void LB_DrawItem(object sender, DrawItemEventArgs e)
{
ListBox lst = sender as ListBox;
Class1 c = (Class1)lst.Items[e.Index];
e.DrawBackground();
e.Graphics.FillRectangle(Brushes.DarkSeaGreen, e.Bounds);
e.Graphics.DrawString(c.Text, LB.Font, SystemBrushes.HighlightText, e.Bounds.Left, e.Bounds.Top);
if (!lst.Controls.Contains(c.UC))
{
lst.Controls.Add(c.UC);
}
c.UC.Top = e.Bounds.Top + HeaderHeight;
}
}
单击按钮即可填充列表:
private void button1_Click(object sender, EventArgs e)
{
UserControl1 uc = new UserControl1();
Class1 c = new Class1(uc, "text 1");
ListDrawer LD = new ListDrawer(listBox1);
listBox1.Items.Add(c);
uc = new UserControl1();
c = new Class1(uc, "text 2");
listBox1.Items.Add(c);
}
希望这个问题可以解决....
干杯, 罗伯特。
【问题讨论】:
-
您在绘制对象时是否尝试过
Refresh()上的Refresh()和/或Update()? -
嗨 Joao,我没有,你知道滚动后触发它们的方法吗?
-
使用位置参数来做,用户控件是相对元素,因此从 (0,0) 开始的位置将相对于它们的容器创建它们
-
项目必须完整地显示在列表框中。例如,列表框的高度必须是项目高度的精确倍数。
-
@ DzNiT0 - 使用位置具有相同的效果,用户控件在第一次绘制时处于正确的位置,但在滚动之后,它们似乎会随着您向右和向下移动一个像素(大约)可以在图片中看到。
标签: c# winforms listbox user-controls