Redrawing a resized owner drawn listbox

For some strange reason the MeasureItem event isn't fired when an owner drawn listbox (or similar control) is resized. If you have lots of items in the listbox with variable height, for example text that needs to wrap, this becomes a problem. I tried different stuff to fix this, but it seems that the MeasureItem event is only fired when things are added or removed from the listbox, so the simplest fix was this:

            listBox1.Resize += new System.EventHandler(listBox1_Resize);

 

            private void listBox1_Resize(object sender, System.EventArgs e)

            {

                  RefreshListBox(sender);

            }

 

            private void RefreshListBox(object sender)

            {

                  ListBox listbox = (ListBox)sender;

                  object[] items = new object[listbox.Items.Count];

                  listbox.Items.CopyTo(items,0);

                  listbox.BeginUpdate();

                  listbox.Items.Clear();

                  listbox.Items.AddRange(items);

                  listbox.EndUpdate();

            }

 

Take a copy of the current items in the box, remove the items and just add them again. Stupid, but as far as I know, this has to be done if you want the correct item height.

No Comments