我有一個ListView我希望調整項目的繪圖(例如突出顯示列表視圖中的某些字符串),但我不想從根本上改變項目的顯示方式。ListView的默認實現OwnerDraw
我已經將OwnerDraw設置爲true,並且可以讓我的頭瞭解如何繪製突出顯示效果,但每當我試圖按照默認實現繪製列表視圖項目的其餘部分時,事情就會出錯,而我留下了一大堆圖形問題,表明實際上我完全出錯了。
有什麼地方可以看到DrawItem
和DrawSubItem
事件的「默認」處理程序是否可以幫助我更好地理解並更輕鬆地調整我的代碼?
僅供參考這裏的一個片段顯示的是我在做什麼:
public MyListView()
{
this.OwnerDraw = true;
this.DoubleBuffered = true;
this.DrawColumnHeader += new DrawListViewColumnHeaderEventHandler(MyListView_DrawColumnHeader);
this.DrawItem += new DrawListViewItemEventHandler(MyListView_DrawItem);
this.DrawSubItem += new DrawListViewSubItemEventHandler(MyListView_DrawSubItem);
}
private void MyListView_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
// Not interested in changing the way columns are drawn - this works fine
e.DrawDefault = true;
}
private void MyListView_DrawItem(object sender, DrawListViewItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
}
private void MyListView_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
string searchTerm = "Term";
int index = e.SubItem.Text.IndexOf(searchTerm);
if (index >= 0)
{
string sBefore = e.SubItem.Text.Substring(0, index);
Size bounds = new Size(e.Bounds.Width, e.Bounds.Height);
Size s1 = TextRenderer.MeasureText(e.Graphics, sBefore, this.Font, bounds);
Size s2 = TextRenderer.MeasureText(e.Graphics, searchTerm, this.Font, bounds);
Rectangle rect = new Rectangle(e.Bounds.X + s1.Width, e.Bounds.Y, s2.Width, e.Bounds.Height);
e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), rect);
}
e.DrawText();
}
我想你需要添加關於什麼錯誤的詳細信息。我測試了你的代碼,它是......好的。它用黃色框突出了「Term」一詞。也許顯示繪圖結果的圖像。 – LarsTech 2012-01-30 16:01:17
@LarsTech我遇到了很多問題,從選擇效果不再可見(可以在上面的示例中看到)到項目文本被「雙重渲染」,並且當我將鼠標懸停在項目上時也消失。我不希望有人能夠神奇地修復所有這些問題(這些問題也會過於具體以至於不能幫助未來的用戶),相反我希望看到一個能夠儘可能接近地呈現所有內容的示例實現。標準實施 – Justin 2012-01-30 16:22:08