您有几种方法可以做到这一点。
如果 Audio 是您的班级 - 您应该重写 ToString 函数:
public override string ToString()
{
return string.Format("{0}_{1}", Artist, Title);
}
如果没有并且您使用 WinForms - 您应该自己实现函数DrawItem 并重绘ListBox。另外,不要忘记将属性DrawMode 更改为值DrawMode.OwnerDrawFixed。它表明,listbox 控件中的所有元素都是手动绘制的。
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Draw the current item text
var currentItem = listBox1.Items[e.Index] as Audio;
var outputStr = string.Format("{0}_{1}", currentItem.Artist, currentItem.Title);
e.Graphics.DrawString(outputStr, e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
实际上,如果您使用 WPF - 您还有第三个变体。但问题是字段Title 和Artist 应该有访问器方法。如果你的类没有它 - 它不起作用。
首先你应该设置ItemsSource
listBox1.ItemsSource = YourList<Artist>();
下一步 - 使用 ListBox 的 ItemTemplate 属性:
<ListBox.ItemTemplate>
<DataTemplate>
<WrapPanel>
<TextBlock Text="{Binding Path=Artist}" />
<TextBlock Text="_" />
<TextBlock Text="{Binding Path=Title}" />
</WrapPanel>
</DataTemplate>
</ListBox.ItemTemplate>
最后一个变体,如果您的字段没有访问器。正如我所说,您拥有的一种方法是继承一个类并实现ToString:
public class MyAudio : Audio
{
public override string ToString()
{
return string.Format("{0}_{1}", Artist, Title);
}
}