ListBox DrawItem

本文关键字:DrawItem ListBox | 更新日期: 2023-09-27 18:17:36

我有这个方法来绘制列表框"txtAcao",它的工作错误:

  private void txtAcao_DrawItem(object sender, DrawItemEventArgs e)
    {
        MyListBoxItem item = txtAcao.Items[e.Index] as MyListBoxItem; // Get the current item and cast it to MyListBoxItem
        if (item != null)
        {
            int index = 0; //Posicoes de inicio do texto
            //Pintando a nome de preto
            string message = item.Message.Substring(0, item.Message.IndexOf(":") + 1);
            e.Graphics.DrawString(message, txtAcao.Font, new SolidBrush(Color.Black), new PointF(index, e.Index * txtAcao.ItemHeight));
            index = item.Message.IndexOf(":") + 1;
            message = item.Message.Substring(index, item.Message.IndexOf("->") - index).Trim();
            index = item.Message.IndexOf(message);
            //Pintando o valor antigo
            e.Graphics.DrawString(message, txtAcao.Font, new SolidBrush(item.ItemColor), new PointF(index, e.Index * txtAcao.ItemHeight));
            message = item.Message.Substring(item.Message.IndexOf("->"), 2);
            index = item.Message.IndexOf("->") + 2;
            //Pintando a seta
            e.Graphics.DrawString(message, txtAcao.Font, new SolidBrush(Color.Black), new PointF(index, e.Index * txtAcao.ItemHeight));

           message = item.Message.Substring(index);
           index = item.Message.IndexOf(message);
            //Pintando o novo valor
           e.Graphics.DrawString(item.Message.Substring(index), txtAcao.Font, new SolidBrush(Color.Blue), new PointF(index, e.Index * txtAcao.ItemHeight));
        }
        else
        {
            e.Graphics.DrawString(txtAcao.Items[e.Index].ToString(), txtAcao.Font, new SolidBrush(txtAcao.ForeColor), new PointF(0, e.Index * txtAcao.ItemHeight));
            // The item isn't a MyListBoxItem, do something about it
        }

但是字符串重叠

索引值总是正确的。有人能帮我吗?

ListBox DrawItem

在调用DrawString时,您使用index变量(字符串中的字符数),但您需要使用测量的文本宽度。试一试:

new PointF(
    e.Graphics.MeasureString(message, txtAcao.Font).Width, 
    e.Index * txtAcao.ItemHeight)
不是

new PointF(index, e.Index * txtAcao.ItemHeight)