C#列表框所有者DrawFixedMode滚动无法正确显示列表
我在C#(windows 64位)中使用一个列表框项目,我想用不同的颜色给不同的项目上色 颜色。 我通过将listbox设置为OwnerDrawFixed并“重载”DrawItem函数来实现这一点C#列表框所有者DrawFixedMode滚动无法正确显示列表,c#,winforms,listbox,smooth-scrolling,C#,Winforms,Listbox,Smooth Scrolling,我在C#(windows 64位)中使用一个列表框项目,我想用不同的颜色给不同的项目上色 颜色。 我通过将listbox设置为OwnerDrawFixed并“重载”DrawItem函数来实现这一点 this.TestList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.TestList.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this
this.TestList.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
this.TestList.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.TestList_DrawItem);
private void TestList_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
TestListItem item = TestList.Items[e.Index] as TestListItem;
bool selected = ((e.State & DrawItemState.Selected) == DrawItemState.Selected);
if (item != null)
{
SolidBrush backgroundBrush = reportsBackgroundBrushSelected;
if (selected)
{
backgroundBrush = reportsBackgroundBrushSelected;
}
SolidBrush foregroundBrush = (selected) ? reportsForegroundBrushSelected : reportsForegroundBrush;
e.Graphics.DrawString( // Draw the appropriate text in the ListBox
item.GetTestName(), // The message linked to the item
TestList.Font, // Take the font from the listbox
new SolidBrush(item.GetColor()), // Set the color
0, // X pixel coordinate
e.Index * TestList.ItemHeight // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox.
);
//background:
e.DrawFocusRectangle();
}
else
{
}
}
选择项目也可以正常工作。
但是,当尝试滚动列表时,列表项会“闪烁”-有时会在单击之前消失
然后再次强制绘制项目。
我的理论是,我可能需要重载scroller事件并调用刷新函数
我非常感谢你的帮助
谢谢,
绝望的
图像:
编辑:
看来e.bounds就是解决方案
滚动和拖动鼠标可能编辑了Y属性。正确的呼叫:
e.Graphics.DrawString( // Draw the appropriate text in the ListBox
item.GetTestName(), // The message linked to the item
TestList.Font, // Take the font from the listbox
new SolidBrush(item.GetColor()), // Set the color
e.Bounds.X, // X pixel coordinate
e.Bounds.Y // Y pixel coordinate. Multiply the index by the ItemHeight defined in the listbox.
);
您熟悉
ListBox.BeginUpdate()吗
和ListBox.EndUpdate()代码>方法。。这听起来像是一个可以用来阻止闪烁的东西a)对我来说不象过载b)你可以/应该使用textrender
而不是graphics.DrawString()
c)你不需要计算X和Y,e.Bounds
已经有了位置d)图像看起来像是存在水平偏移问题。我已尝试在填充列表的位置添加being/end更新。这没用。我不确定水平偏移的问题,因为当我滚动项目时,直到我单击它们(调用draw item?)才可见。这就是我所说的“重载”:this.TestList.DrawMode=System.Windows.Forms.DrawMode.OwnerDrawFixed;this.TestList.DrawItem+=new System.Windows.Forms.DrawItemEventHandler(this.TestList\u DrawItem);尝试从e.Bounds
获取X,Y。没有理由不使用事件提供的内容。