如果内容字符串宽度大于ListBox宽度,则将DotNet ListBox项目Winforms自动换行?

嗯,嗯,这意味着一些线条应该是两行的。 我的老板认为这是一个更简单的解决方案,比限制显示的文字以适应宽度而不喜欢水平滚动条> _ <

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); } 

有用的链接

看看这个答案。 它使用包含文本的文本块覆盖列表框的模板。 希望它有用。 为了解决你的问题,我认为你应该添加:ScrollViewer.Horizo​​ntalScrollBarVisibility =“已禁用”。 在这里找到它

 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 

然后上面的函数可以适当地测量字符串并绘制它。 🙂

要使绑定正确,请务必将“lst.Items.Count> 0”检查添加到lst_MeasureItem函数。 这是我的例子:

  if (lst.Items.Count > 0) { e.ItemHeight = (int)e.Graphics.MeasureString(lst.Items[e.Index].ToString(), lst.Font, lst.Width).Height; } 

之后其他所有东西似乎都很好用。