简体   繁体   中英

.NET WinForm ComboBox - How to alter the DropDown behavior

I've got a fairly long list in a ComboBox, and I want the DropDown behavior to be different.

Normally, when you click the arrow, the list expands showing all options, starting with the selected option. Options listed above the selected option are hidden, but can be seen by scrolling up.

I want the list to scroll up a bit, showing the selected option in the middle of the list, whenever possible.

I've seen ways to do this in a Scrollbar enabled FlowLayoutPanel, but I've had no luck with the DDL. The list is over 50 items long, so simply showing the whole list isn't practical.

In my opinion, you can achieve the effect by using your own drawing item method. By this I mean, you attach an handler to the DrawItem event, then in the handler, you get all your required data that you wish to show. After that you draw it to the screen.

For example:

private void myComboBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            if ( boundDataSource.Count > 0 && e.Index >= 0 )
            {
              if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                {
                    //Get the data here
                    string dataToShow=  GetDataToShow()

                    e.DrawFocusRectangle();

                    System.Drawing.Graphics g = e.Graphics;
                    Rectangle r = e.Bounds;             


                    e.Graphics.FillRectangle(new SolidBrush(Color.Blue), r);
                    g.DrawStringdataToShow, e.Font, Brushes.White, r, stringFormat);
                    e.DrawFocusRectangle();
                    g.Dispose();
                }



            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM