这意味着某些行应该是双行大小。我的老板认为这是比限制显示文本适应宽度并且不喜欢水平滚动条更简单的解决方案。
lst.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
lst.MeasureItem += lst_MeasureItem;
lst.DrawItem += lst_DrawItem;
private void lst_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = (int)e.Graphics.MeasureString(lst.Items[e.Index].ToString(), lst.Font, lst.Width).Height;
}
private void lst_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
e.Graphics.DrawString(lst.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
}
private void lst_MeasureItem(object sender, MeasureItemEventArgs e)
{
e.ItemHeight = (int)e.Graphics.MeasureString(lst.Items[e.Index].ToString(), lst.Font, lst.Width).Height;
}
private void lst_DrawItem(object sender, DrawItemEventArgs e)
{
e.DrawBackground();
e.DrawFocusRectangle();
e.Graphics.DrawString(lst.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds);
}
lst.Items[e.Index].ToString()
使用属性的强制转换版本进行绑定。因此,如果你的绑定源是类对象 Car,则它看起来像:
((Car)lst.Items[e.Index]).YourDisplayProperty
if (lst.Items.Count > 0)
{
e.ItemHeight = (int)e.Graphics.MeasureString(lst.Items[e.Index].ToString(), lst.Font, lst.Width).Height;
}
在那之后,其他一切似乎都很好运行。
ListBox
缓存了项目的高度,这是好的。问题在于,如果ListBox
被调整大小,它不会重新计算高度!我正在尝试在resize
中清除项目高度缓存的某种方法,而不需要删除和添加它们,但我找不到任何方法。至少有记录的方法。 - Diego C Nascimento