我写了想重给ListBox,让ListBox的每一项都是一个控件,但出现了不能及时重绘的问题,代码如下:
private class OwnerDrawListBox : ListBox { private void Add(Control item) { this.Items.Add(item); var topIndent = this.Owner.TopIndex * this.ItemHeight; this.Controls.Add(item); var rect = this.GetItemRectangle(this.Items.Count - 1); item.Location = rect.Location; item.Left += 20; item.Width = 100; } protected override void OnDrawItem(DrawItemEventArgs e) { using (Graphics g = e.Graphics) { Brush myBrush = Brushes.Black; if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) e.Graphics.FillRectangle(new SolidBrush(System.Drawing.SystemColors.MenuHighlight), e.Bounds); else e.Graphics.FillRectangle(new SolidBrush(this.BackColor), e.Bounds); e.Graphics.DrawString(this.GetItemText(this.Items[e.Index]), e.Font, myBrush, e.Bounds.X, e.Bounds.Y); e.DrawFocusRectangle(); } } }
调用是时的代码:
listBoxEx1.ItemHeight = 50; listBox1Ex.DisplayMember = "Text"; for (var i = 0; i < 10; i++) { listBoxEx1.Add(new Button { Text = i.ToString() }); }
问题是初始化后正常,但滚动条滚动时,按钮不能及时刷新,如下两幅图中第二幅滚动后就文字就不同步了:
请问这个要怎么刷新呀?我自己试了一些方法,都不行。我发现当窗体失去焦点时,按钮会自动刷新,文字就同步了,不知道是否有助于分析问题。