15

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

4

4 回答 4

38
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);
}
于 2013-07-14T14:09:49.650 回答
2
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

那么上面的函数就可以对字符串进行适当的测量并绘制出来了。:)

于 2014-10-16T15:47:39.893 回答
0

要使绑定正确,请务必将检查“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;
 }

在那之后,其他一切似乎都运行良好。

于 2015-01-29T18:54:14.200 回答
0

有用的链接

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

于 2013-07-12T11:17:54.787 回答