2016-01-09 105 views
0

編輯:我已經想出了爲什麼文本繪製爲粗體。因爲第一列調用OnDrawSubItem兩次。有人知道爲什麼ListView刷新不能正常工作


我已經創建了一個繼承自ListView類的自定義控件。我已經覆蓋OnDrawSubItem和OnDrawItem方法,如下所示:

protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) 
    { 
     Rectangle rowBounds = e.SubItem.Bounds; 
     Rectangle labelBounds = e.Item.GetBounds(ItemBoundsPortion.Label); 
     Rectangle bounds = new Rectangle(rowBounds.Left + 5, rowBounds.Top + 2, labelBounds.Width - 5, rowBounds.Height + 2); 
     if (e.Item.Selected) 
      e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.White, bounds); 
     else 
      e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.Black, bounds); 

    } 

    protected override void OnDrawItem(DrawListViewItemEventArgs e) 
    { 
     e.DrawBackground(); 
     if (e.Item.Selected) 
     { 
      Rectangle rowBounds = e.Bounds; 
      Rectangle bounds = new Rectangle(0, rowBounds.Top, rowBounds.Width, rowBounds.Height); 
      e.Graphics.FillRectangle(Brushes.Gray, bounds); 
     } 
    } 

但是有些東西不能正常工作。當我添加一些項目到ListView時,文本有點厚。列表視圖被放置在一個選項卡中。當我切換到另一個選項卡並回到帶有listview的選項卡時,文本看起來很好。於是,我就做這一點,並試圖在項目增加操作的末尾添加listView.Refresh(),但沒有奏效:

//code 1 
foreach(string s in new string[] { "item1", "item2", "item3", "item4", "item5" }) 
{ 
    listView.Items.Add(s); 
} 
listView.Refresh(); 

輸出是:

我也嘗試刷新在每次迭代,這是一個好一點,但最後一個元素沒有被刷新:

//code 2 
foreach(string s in new string[] { "item1", "item2", "item3", "item4", "item5" }) 
{ 
    listView.Items.Add(s); 
    listView.Refresh(); 
} 

輸出:

當切換選項卡時,所有文本都是應該如何處理的。

我的兩個問題在這裏:

  1. 爲什麼加入時,他們的文字渲染不好?
  2. 代碼1和代碼2有什麼區別?我認爲他們應該以同樣的方式工作。

另外,也許值得一提的是,如果我添加第二列,第二列呈現良好。

回答

0

您是否試過在DrawString之前調用e.DrawBackground()?這可能會擺脫厚厚的文字。

+0

當我點擊某件物品時,它刪除了文字。 –