近日在做項目時,需要調整listbox的行間距大小,網上查找了一些資料,方法如下
在使用Listbox的時候,ItemHeight的默認值是12,當在屬性窗口里更改它時,改了又變回去了,這是因為Listbox默認是不能更改ItemHeight的。想要更改的話,需要這樣做:
首先設置DrawMode屬性為OwnerDrawVariable,自己畫Listbox。
然后處理DrawItem和MeasureItem兩個事件,DrawItem是在顯示項時觸發,MeasureItem是在要計算項的寬高時觸發。在DrawItem里重新繪制項目,如下:
1:屬性位置如下:(屬性可以不用修改,直接在代碼里修改)
2:代碼如下:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(e.BackColor), e.Bounds);
if (e.Index >= 0)
{
StringFormat sStringFormat = new StringFormat();
sStringFormat.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(((ListBox)sender).Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds, sStringFormat);
}
e.DrawFocusRectangle();
}
private void listBox1_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = e.ItemHeight + 8;//這里設置行間距,也可以把8改為其他的任何數字
}