0

我用列表中的项目填充组合框,按组合框中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;
 }

我的问题是:我怎样才能告诉组合框重新计算它的项目列表并动态重绘它,而不仅仅是隐藏和再次显示这个列表?

4

3 回答 3

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.
于 2013-06-19T18:01:21.940 回答
0

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

ComboBox 列表控件宿主

于 2013-06-19T13:42:54.790 回答
0

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

于 2013-06-19T13:43:53.370 回答