0

我有这个方法可以在 ListBox“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
        }

但是字符串重叠。

索引值总是正确的。谁能帮我?

4

1 回答 1

0

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

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

代替

new PointF(index, e.Index * txtAcao.ItemHeight)
于 2013-06-07T15:41:03.930 回答