1

I have a ComboBox (ToolStripCombobox, to be more precise) filled with items of type KeyValuePair<Int32, FontFamily>. I managed to have the Items beeing painted manually by using the DrawItem event. So every Item is painted with the FontFamily of the corresponding KeyValuePair. This works fine for the DropDownList, but when I select an Item out of the List and the list closes, the text in the ComboBox says something like "[21, [FontFamily: Name=Arial]]" which is most likely the result of SelectedItem.ToString().

Any ideas how to solve this problem?

here is the code of my custom DrawItem method:

private void fontComboBoxDrawItem(object sender, DrawItemEventArgs e)
        {
            e.DrawBackground();
            if ((e.State & DrawItemState.Focus) != 0)
            {
                e.DrawFocusRectangle();
            }
            Brush objBrush = null;

            var itemToDraw = this.fontComboBox.Items[e.Index];

                KeyValuePair<Int32, FontFamily> windowsFontItem = (KeyValuePair<Int32, FontFamily>)itemToDraw;
                objBrush = new SolidBrush(e.ForeColor);
                e.Graphics.DrawString(windowsFontItem.Value.Name, new Font(windowsFontItem.Value, e.Font.Size), objBrush, e.Bounds);
            if (objBrush != null)
            {
                objBrush.Dispose();
            }
            objBrush = null;
        }

Update:

It works as expected, when I set the DropDownStyle of the ComboBox to ComboBoxStyle.DropDownList

But I´d rather use ComboBoxStyle.DropDown, so you can edit the Text to search for Fonts.

tafkab76
  • 465
  • 1
  • 6
  • 18
  • 1
    You just can't. Custom drawing is only implemented for the dropdown list. But not for TextBox and thus not for the textbox portion of the ComboBox. A restriction that's been around for 30 years, back when Windows had to run on very limited hardware. They had to cheat to make edit controls responsive and did so by painting without using WM_PAINT. Thirty years of appcompat, edit controls have been hacked every possible way imaginable, prevented them from ever fixing that. It isn't very obvious why it is necessary from the snippet, looks like you only have to change the Font property. – Hans Passant Sep 17 '15 at 11:10
  • Unfortunatelay, I´m kinda forced to use Windows Forms. So I wil just go with the ComboBoxStyle.DropDownList soultion. – tafkab76 Sep 18 '15 at 11:22

0 Answers0