Winforms DotNet ListBox items to word wrap if content string width is bigger than ListBox width?

后端 未结 4 1046
死守一世寂寞
死守一世寂寞 2020-12-03 11:37

Ehm, umm, this means some lines should be two-lined in size. My boss think this is more simple solution, than limit displayed text to fit width and don\'t like horizontal sc

4条回答
  •  广开言路
    2020-12-03 12:11

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

    To get the right display member to show up when data binding, replace

    lst.Items[e.Index].ToString()
    

    with a casted version of the property. So if your binding source is class object Car it would look like

    ((Car)lst.Items[e.Index]).YourDisplayProperty
    

    Then the above functions can appropriately measure the string and draw it. :)

提交回复
热议问题