You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ComboBox中使用字典隐藏UI输出中的方括号?

解决ComboBox显示项带方括号的问题

问题出在自定义绘制项时,直接调用cbx.Items[e.Index].ToString()——你的数据源是KeyValuePair<string, string>的列表,这个类型的ToString()会返回类似[Key, Value]的格式,这就是方括号的来源。

修复方案

方案1:使用GetItemText获取DisplayMember指定的文本

这个方法会自动根据你设置的DisplayMember返回对应的值,无需手动处理类型:

private void conn_mode_DrawItem(object sender, DrawItemEventArgs e)
{       
    ComboBox cbx = sender as ComboBox;
    if (cbx != null)
    {
        // 绘制背景
        e.DrawBackground();

        if (e.Index >= 0)
        {
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;

            Brush brush = new SolidBrush(cbx.ForeColor);
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                brush = SystemBrushes.HighlightText;

            // 获取正确的显示文本
            string displayText = cbx.GetItemText(cbx.Items[e.Index]);
            // 绘制文本
            e.Graphics.DrawString(displayText, cbx.Font, brush, e.Bounds, sf);
        }
    }
}

方案2:强转成KeyValuePair后取Value

因为你明确知道数据源是KeyValuePair<string, string>,可以直接强转获取Value:

private void conn_mode_DrawItem(object sender, DrawItemEventArgs e)
{       
    ComboBox cbx = sender as ComboBox;
    if (cbx != null)
    {
        // 绘制背景
        e.DrawBackground();

        if (e.Index >= 0)
        {
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;

            Brush brush = new SolidBrush(cbx.ForeColor);
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                brush = SystemBrushes.HighlightText;

            // 强转成KeyValuePair并获取Value
            var item = (KeyValuePair<string, string>)cbx.Items[e.Index];
            string displayText = item.Value;
            // 绘制文本
            e.Graphics.DrawString(displayText, cbx.Font, brush, e.Bounds, sf);
        }
    }
}

另外注意:你的事件方法名是cur_mul_DrawItem,但ComboBox变量名是conn_mode,要确保事件绑定的是conn_mode的DrawItem事件,否则自定义绘制不会生效。

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 04:55:32