如果你有寫視窗程式的經驗, 應該多少都會用到ListBox這個物件

但你可能會發現, ItemHeight怎麼調就是沒反應...?

下面是我查閱網路資料後的心得, 教你如何自訂ListBox Items.

先來個預覽圖吧:

2222.png

 

 

開始囉:

首先, 將你的listBox's Property當中的[ DrawMode ]設定為[ OwnerDrawVariable ]

這時候你應該會發現Design Panel上頭的listBox Items消失了

別慌張, 這是正常的, 不影響接下來的操作, 因為我們要在Runtime時才產生Item物件

這時, 你可以修改ItemHeight屬性囉, 接下來會用到...

接著, 新增以下兩個listBox事件: DrawItem() && MeasureItem()

接下來, 進入程式碼編輯:

private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
    // 這裡告訴程式在繪製項目前要做的事情
}

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
    // 這裡告訴程式你要怎麼繪製你的項目
}

好了, 大致上已經準備完畢

接下來便可以自由發揮, 繪製一個屬於你的listBox Items...

 

下面是簡單的範例:

 

  private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
  {
      //
取得目前物件的高度 (可自訂, 或著像下面這樣取值)
      e.ItemHeight = ((ListBox)sender).ItemHeight;
  }

  private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
  {
      //
取得目前物件的外框
      Rectangle rect = e.Bounds;
      //
取得目前物件的前景顏色
      Brush brush = new SolidBrush(e.ForeColor);
      //
取得目前物件的文字內容
      String innerText = listBox1.Items[e.Index].ToString();
      //
繪製目前物件的背景
      e.DrawBackground();
      //
繪製目前物件的虛框
      e.DrawFocusRectangle();
      //
繪製目前物件的內容
      e.Graphics.DrawString(innerText, e.Font, brush, rect);
  }

 

進階變化:

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
          // 當項目正被選取時, 如何繪製
    else
          // 當項目未被選取時, 如何繪製
}
 

 

參考資料: C#设置Listbox的ItemHeight - 虛夜宮

arrow
arrow
    全站熱搜

    沒 發表在 痞客邦 留言(0) 人氣()