tafkab76
tafkab76

Reputation: 475

Windows Forms: Manually paint SelectedItem of ComboBox

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.

Upvotes: 1

Views: 559

Answers (0)

Related Questions