0

我创建了一个自定义组合框,它使用列表框控件的自定义实例作为下拉菜单。

为了自定义列表框的选择突出显示,我不得不将其“DrawMode”属性更改为“OwnerDrawFixed”并添加以下代码:

Private Sub _listBox_DrawItem(sender As Object, e As DrawItemEventArgs)
    If e.Index >= 0 Then
        e.DrawBackground()
        If (e.State And DrawItemState.Selected) = DrawItemState.Selected Then
            Using br = New LinearGradientBrush(e.Bounds, ColorSelectionListbox, ColorSelectionListbox, 0)
                e.Graphics.FillRectangle(br, e.Bounds)
            End Using
        End If
        Using b As New SolidBrush(ColorTextListbox)
            e.Graphics.DrawString(_listBox.GetItemText(_listBox.Items(e.Index)), e.Font, b, e.Bounds)
        End Using
        e.DrawFocusRectangle()

        RaiseEvent DrawItem(Me, e)
    End If
End Sub

但是这样一来,我为其设置的宽度将被忽略,并变为 15 像素左右的固定宽度。

如何设置自绘控件的宽度?目前我将其作为财产:

Public Property DropDownWidth() As Integer
    Get
        Return _dropDownWidth
    End Get
    Set(value As Integer)
        _dropDownWidth = value
        _listBox.Width = value
        Invalidate(True)
    End Set
End Property
4

1 回答 1

0

下面是相关的其余代码,但没关系。我通过设置 to 的属性解决了这个Autosize问题。我将其设置为以显示列表中的所有项目(无需定义下拉最大值),但由于某种原因,当设置为._controlHostFalseTrueDrawModeOwnerDraw

    _listBox = New ListBox()
    _listBox.IntegralHeight = True
    _listBox.BorderStyle = BorderStyle.FixedSingle
    _listBox.SelectionMode = SelectionMode.One
    _listBox.BindingContext = New BindingContext()
    _dropDownWidth = Me.Width
    _listBox.Width = _dropDownWidth

    _controlHost = New ToolStripControlHost(_listBox)
    _controlHost.Padding = New Padding(0)
    _controlHost.Margin = New Padding(0)
    _controlHost.AutoSize = False 'Used to be variable property _dropDownAutoSize

    _popupControl = New ToolStripDropDown()
    _popupControl.Padding = New Padding(0)
    _popupControl.Margin = New Padding(0)
    _popupControl.AutoSize = True '
    _popupControl.DropShadowEnabled = False
    _popupControl.Items.Add(_controlHost)
于 2013-09-11T09:06:17.190 回答