Winform Combobox仅为选中项设置特殊自定义字体的实现咨询
解决方案
你原来的实现思路错误:自绘ComboBox的所有内容渲染逻辑都必须在DrawItem事件中处理,SelectedIndexChanged事件中直接操作控件Graphics对象绘制的内容会被控件重绘覆盖,无法持久生效。
具体修改步骤
- 删掉你写的
cmbFontStyle_SelectedIndexChanged事件的全部代码,该逻辑完全不需要。 - 修改
cmbFontStyle_DrawItem方法,增加组合框编辑区域的绘制判断:当绘制的是输入框区域的内容时,使用FontStyleForDisplay字体渲染,下拉列表内的项保持原有自定义字体。 - (可选修正)你原有的
cmbFontStyle_MeasureItem存在两处小问题:e.Index是整数类型,用字符串匹配逻辑不严谨;intcmbFontStyleTotalHeight未赋值会导致下拉高度不符合预期,可同步修正。
最终可用代码
修改后的DrawItem事件
Private Sub cmbFontStyle_DrawItem(ByVal sender As Object, ByVal e As DrawItemEventArgs) e.DrawBackground() If e.Index < 0 Then Return ' 无选中项时直接返回 Dim myItem As CorpusFontStyleItem = DirectCast(cmbFontStyle.Items(e.Index), CorpusFontStyleItem) Dim useFont As Font ' 判断当前是否绘制组合框的输入编辑区域 If (e.State And DrawItemState.ComboBoxEdit) = DrawItemState.ComboBoxEdit Then useFont = FontStyleForDisplay Else useFont = myItem.fontTextStyle End If e.Graphics.DrawString(myItem.strTextStyleName, useFont, New SolidBrush(Color.Black), e.Bounds) e.DrawFocusRectangle() End Sub
修正后的MeasureItem事件(可选)
Private Sub cmbFontStyle_MeasureItem(ByVal sender As Object, ByVal e As MeasureItemEventArgs) ' 原代码用字符串判断e.Index不严谨,改为整数判断 Select Case e.Index Case 0 e.ItemHeight = 50 Case 1 e.ItemHeight = 40 Case 2 e.ItemHeight = 30 Case 3 e.ItemHeight = 20 Case 4 e.ItemHeight = 10 End Select ' 赋值总高度,修正下拉高度问题 intcmbFontStyleTotalHeight = 50 + 40 + 30 + 20 + 10 cmbFontStyle.DropDownHeight = intcmbFontStyleTotalHeight End Sub
修改完成后即可实现你要的效果:下拉列表内的选项保留各自的自定义字体,选中后输入框中显示的内容使用统一的FontStyleForDisplay字体渲染。
内容的提问来源于stack exchange,提问作者8oris
相关产品推荐
相关产品推荐

