带有字典数据源的ListBox显示完整的KeyValuePair,而不仅仅是值

时间:2018-04-05 19:47:01

标签: c# winforms dictionary listbox datasource

我有一个列表框,其中包含Dictionary<int, UmfTag>作为其DataSource。我已将列表框的DisplayMember设置为“Value”,将ValueMember设置为“Key”,但是当显示列表框时,它会显示所有KeyValuePairs而不仅仅是值。

我的代码:

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

以上是我在列表框中想要的内容。不幸的是,出于某种原因,列表框显示整个KeyValuePair而不仅仅是Value,因此它显示

[12, 0012 - Name]

从我的代码中可以看出,我明确地将DisplayMember设置为“Value”。那为什么不起作用?我尝试将Dictionary<int, UmfTag>转换为List<KeyValuePair<int, UmfTag>>,但问题仍然存在。

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

我一定做错了,但我的代码看起来与使用Dictionaries和DataSources的所有其他主题相同,那么我的问题是什么?

修改 因为我需要对列表中的某些项进行粗体和斜体化,所以我编写了自己的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()的第一个参数的值。此值是完整的KeyValuePair。我不知道为什么会这样,但我想我只需要更改那行代码来获取Item的Value属性。

1 个答案:

答案 0 :(得分:1)

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

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

ToString