当它已经在屏幕上显示时,如何动态更改ComboBox的下拉列表?

时间:2013-06-19 13:35:59

标签: c# winforms combobox

我使用列表TownList中的项目填充组合框,在组合框中按文本searchString过滤

List<Towns> towns = PIKBLL.TownList.FindAll(p => p.Name.Contains(searchString)); (sender as ComboBox).DataSource = towns;

每次用户在组合中输入文字时都会这样做。

另外,在同一个事件处理程序中,我告诉组合框以这种方式显示它:cb.DroppedDown = true;一切正常,但是......当过滤结果数越来越小时,组合框的下拉高度保持不变

我试图将这样的方法称为:

cb.PerformLayout();
cb.Refresh();
cb.Update();

我也试过这个:

if (towns.Count != 0)
{
    if (towns.Count * cb.ItemHeight < 300)
        cb.DropDownHeight = towns.Count * cb.ItemHeight;
     else
        cb.DropDownHeight = cb.ItemHeight * 15;
 }

我的问题是:我怎么能告诉combobox重新计算它的项目列表并动态地重绘它而不只是隐藏并再次显示这个列表?

3 个答案:

答案 0 :(得分:1)

如果您想查看代码,我会在这里发布最好的代码,但不完整但可以帮助您入门:

    [DllImport("user32")]
    private static extern int GetComboBoxInfo(IntPtr hwnd, out COMBOBOXINFO comboInfo);                
    [DllImport("user32")]
    private static extern int GetWindowRect(IntPtr hwnd, out RECT rect);
    [DllImport("user32")]
    private static extern int MoveWindow(IntPtr hwnd, int x, int y, int width, int height);
    struct RECT
    {
        public int left, top, right, bottom;
    }
    struct COMBOBOXINFO
    {
        public int cbSize;
        public RECT rcItem;
        public RECT rcButton;
        public int stateButton;
        public IntPtr hwndCombo;
        public IntPtr hwndItem;
        public IntPtr hwndList;//This is the Handle of the drop-down list, the one we care here.
    }
    COMBOBOXINFO comboInfo = new COMBOBOXINFO();
    comboInfo.cbSize = Marshal.SizeOf(comboInfo);//Set the size needed to hold the data of the drop-down list Handle
    GetComboBoxInfo(comboBox.Handle, out comboInfo);//Get the Handle of the drop-down list of the combobox and pass out to comboInfo
    //You use the MoveWindow() function to change the position and size of a window via its Handle.
    //show the drop-down list
    comboBox.DroppedDown = true;
    //You use the GetWindowRect() to get the RECT of a window via its Handle
    //this method just sets the new Width for a window
    private void SetWidth(IntPtr hwnd, int newWidth){
       RECT rect;
       GetWindowRect(hwnd, out rect);
       MoveWindow(hwnd, rect.left, rect.top, newWidth, rect.bottom-rect.top);
    }
    //Test on a drop-down list of a combobox
    SetWidth(comboInfo.hwndList, 400);
    //....
    //Your problem is change the Height not the Width of the drop-down list of a combobox
    //You have to notice that when the drop-down list is really dropped down, you will have to set new Height for the drop-down list only. However if it is popped-up, you will have to set new Height and calculate the new `Top` of the drop-down list to move the drop-down list accordingly. I've tested successfully.

答案 1 :(得分:0)

我认为没有办法强制普通的ComboBox进入这种行为。您将不得不创建自己的ComboBox来实现它。这篇文章的一个很好的起点是:

ComboBox List Control Host

答案 2 :(得分:0)

您希望在用户键入其searchString时更新已打开的ComboBox。您是否考虑过使用AutocompleteBox?它也会这样做。