我试图隐藏UI输出中的方括号。
我认为这是一个很容易的变通办法,但我想不出来。
我的代码添加项目到组合框:
conn_mode.DataSource = new Dictionary<string, string>()
{
{"1", "WiFi"},
{"2", "GSM"},
{"3", "Offline"},
}.ToList();
conn_mode.ValueMember = "Key";
conn_mode.DisplayMember = "Value";
我使用这段代码将组合框中的项目居中对齐:
private void cur_mul_DrawItem(object sender, DrawItemEventArgs e)
{
ComboBox cbx = sender as ComboBox;
if (cbx != null)
{
// Always draw the background
e.DrawBackground();
// Drawing one of the items?
if (e.Index >= 0)
{
// Set the string alignment. Choices are Center, Near and Far
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
// Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings
// Assumes Brush is solid
Brush brush = new SolidBrush(cbx.ForeColor);
// If drawing highlighted selection, change brush
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
brush = SystemBrushes.HighlightText;
// Draw the string
e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, brush, e.Bounds, sf);
}
}
2条答案
按热度按时间xpszyzbs1#
无论如何填充
ComboBox
,始终调用GetItemText
方法来获取item的文本。如果需要显示
ValueMember
+DisplayMember
这样的格式化字符串,此处的数据源是Dictionary<string, string>
,则这些项是KeyValuePair<string, string>
类型的集合。因此:否则,当您传递
cbx.Items[e.Index].ToString()
时,您将得到.ToString()
方法覆盖为KeyValuePair<TKey, TValue>
类型返回的内容。旁注
sf
和brush
示例,或使用using
语句创建它们。TextRenderer
在控件上绘制文本。ig9co6j12#
在组合框中添加字典值
enter image description here
使用下面的代码在添加到组合框中时删除方括号。
enter image description here