2013-06-07 2 views
0

У меня есть этот метод DrawItem на ListBox "txtAcao", он работает неправильно:ListBox DrawItem

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 
     } 

Но строки накладываются.

Значение индекса всегда верно. Может кто-нибудь мне помочь?

ответ

0

При вызовах DrawString вы используете переменную index (количество символов в строке), но вместо этого вам нужно использовать измеренную ширину текста. Попробуйте:

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

вместо

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

Works, спасибо !! –

Смежные вопросы