如何在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
相关产品推荐
相关产品推荐

