带有字典数据源的列表框显示完整的键值对,而不仅仅是值



我有一个列表框,其中Dictionary<int, UmfTag>作为其数据源。我已经将列表框的DisplayMember设置为"Value",将ValueMember设置为"Key",但是当列表框显示时,它会显示所有KeyValuePair,而不仅仅是值。

我的代码:

listBoxAllTags.DataSource = new BindingSource(punchedTagDict, null);
listBoxAllTags.DisplayMember = "Value";
listBoxAllTags.ValueMember = "Key";

每个 KeyValuePair 中的值是我的自定义对象 UmfTag。除其他属性外,它还包含 ID 和说明。UmfTag 的 ToString() 方法返回String.Format("{0:D4} - {1}", Id, Description)。例如,对于具有Id = 12Description = "Name"的 UmfTag,值将显示为

0012 - Name

以上是我在我的列表框中想要的。不幸的是,由于某种原因,列表框显示整个键值对,而不仅仅是值,因此它显示

[12, 0012 - Name]

正如你从我的代码中看到的,我显式地将DisplayMember设置为"Value"。那么为什么这不起作用呢?我尝试将Dictionary<int, UmfTag>转换为List<KeyValuePair<int, UmfTag>>,但问题仍然存在。

我可以将字典转换为List<UmfTag>并忽略键(因为键是 UmfTag 本身中的 ID),但我想将此集合保留为字典。如果必须,我可以从列表中重建字典,但这似乎效率低下。

我一定做错了什么,但我的代码似乎与使用字典和数据源的所有其他主题相同,所以我的问题是什么?

编辑:因为我需要粗体和斜体列表中的某些项目,所以我编写了自己的DrawListBox方法,每当调用listBoxAllTags_DrawItem时都会调用该方法。这是我的方法:

private void DrawListBox(object sender, DrawItemEventArgs e, ListBox listBox, Dictionary<int, UmfTag> searchedDict)
{
if(e.Index < 0) return;
e.DrawBackground();
FontStyle fontStyle = FontStyle.Regular;
Brush brush = Brushes.Black;
// Embolden the first x items, where x = the number of searched results
if(e.Index < searchedDict.Count)
fontStyle = FontStyle.Bold;
// Make the selected item have white font (so you can see it over the blue background)
if((e.State & DrawItemState.Selected) == DrawItemState.Selected)
brush = Brushes.White;
e.Graphics.DrawString(listBox.Items[e.Index].ToString(), new Font("Arial", 8, fontStyle), brush, e.Bounds);
e.DrawFocusRectangle();
}

我在此方法中放置了一个断点,并调查了e.Graphics.DrawString调用的第一个参数的值,listBox.Items[e.Index].ToString()。此值是完整的键值对。我不知道为什么会这样,但我想我只需要更改那行代码即可获取 Item 的值属性。

要获取ComboBoxListBox中的项目文本,您应该始终使用GetItemText方法。

该方法检查是否设置了ComboBoxDisplayMember属性,然后返回在传递给该方法的对象的DisplayMember属性中指定的成员的字符串表示形式,否则返回对象的ToString

var txt = listBox1.GetItemText(listBox1.Items[e.Index]);

相关内容

最新更新