How do I make a ListBox refresh its item text?

前端 未结 10 1968
后悔当初
后悔当初 2020-12-03 04:42

I\'m making an example for someone who hasn\'t yet realized that controls like ListBox don\'t have to contain strings; he had been storing formatted strings and

10条回答
  •  [愿得一人]
    2020-12-03 04:51

    If you use a draw method like:

    private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();
        e.DrawFocusRectangle();
    
        Sensor toBeDrawn = (listBox1.Items[e.Index] as Sensor);
        e.Graphics.FillRectangle(new SolidBrush(toBeDrawn.ItemColor), e.Bounds);
        e.Graphics.DrawString(toBeDrawn.sensorName, new Font(FontFamily.GenericSansSerif, 14, FontStyle.Bold), new SolidBrush(Color.White),e.Bounds);
    }
    

    Sensor is my class.

    So if I change the class Color somewhere, you can simply update it as:

    int temp = listBoxName.SelectedIndex;
    listBoxName.SelectedIndex = -1;
    listBoxName.SelectedIndex = temp;
    

    And the Color will update, just another solution :)

提交回复
热议问题