更改自己的类库名称以添加到listboxitem

时间:2015-08-22 07:09:39

标签: c# winforms

我有对象Audio,其属性为“标题”,“艺术家”等。 我将其添加到ListboxItem,内容变为

  

{audio202738880_386844236}

这是screenshot

如何改变这个基础:{audio202738880_386844236}来重视我想要的东西(ex audio.Artist +“ - ”audio.Title)?

2 个答案:

答案 0 :(得分:1)

您必须覆盖ToString()方法。此方法用于确定列表框中显示的内容。

public override string ToString()
{
    return "Whatever You can construct";
}

您可以从类中的属性构造返回值,以对该对象进行合理的字符串表示。

如果它不是您的类,您可以创建自己的类继承自Audio类,将覆盖放在那里并在代码中使用该新类。除ToString()函数外,它的行为完全相同。仅当Audio未标记为sealed时才有效。

public class MyAudio : Audio
{

    public override string ToString()
    {
        return "Whatever You can construct";
    }
}

由Moe Farag添加

如果已经有ToString()基类实现,您可能需要将new标记为override。但是,每当使用MyAudio方法时,您必须确保使用子类(在本例中为ToString()),以便使用新的实现。

public class MyAudio : Audio
{

    public new string ToString()
    {
        return "Whatever You can construct";
    }
}

答案 1 :(得分:0)

你有几种方法可以做到这一点。 如果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 - 你有第三种变体。但问题是字段TitleArtist应该有访问权限方法..如果您的课程没有 - 它不起作用。 首先,您应该设置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);
   }
}