views:

3734

answers:

3

Hi,

I have a few images with some text, I need to show the image with the relevant text in a listbox.

Browsing google I came across this sample class,

public class Customer
{

    public string Fname;

    public string Lname;

public Customer(string firstName, string lastName)
{
 Fname = firstName;
 Lname = lastName;
}

public override string ToString()
{
 return Fname + " " + Lname;
}
}

lstCustomers.Items.Add(new Customer("Foo","Bar"));

The above code works fine as it only returns string, how do I return an image and a string together so that it gets added to the listbox?

Best Regards

@nand

+2  A: 

You can't (without hacking around) put images in ListBoxes.

You can put them in ListViews.

You need to put your image(s) in an ImageList component, then attach the ImageList to your listview. Of course, you can encapsulate your image in your class by adding an Image property and adding that to the ImageList.Items collection.

Then for each ListViewItem in the List, set the ImageIndex property to the index of the image in the listview.

All this can be done using the designer.

Program.X
A: 

You can add bitmapsource objects to a listboxitem and add it to listbox. Check this thread. http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/f6b7f985-f11b-4d7f-845a-44851360ee1f/

Anirudh Goel
A: 

Just use a DataTemplate to display your objects in the ListBox.

Create a data object that contains string properties and an Image property:

public class Img
{
    public Img(string value, Image img) { Str = value; Image = img; }
    public string Str { get; set; }
    public Image Image { get; set; }
}

Create a DataTemplate to display this:

<ListBox x:Name="lstBox">
    <ListBox.ItemTemplate>
        <DataTemplate DataType="{x:Type local:Img}">
            <StackPanel>
                <TextBlock Margin="3" Text="{Binding Str}"/>
                <ContentControl Margin="3" Content="{Binding Image}"/>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Now add the Img items (or your data objects) to the ListBox like so:

lstBox.Items.Add(new Img("Value", myImage));
Josh G
Assumes that you are using WPF...
Josh G
Does this work for winforms as well, not sure about the datatemplate and how to create this on a form?Thanks.
flavour404
No this does not work for Windows Forms. Window Forms does not have DataTemplates or XAML. For Windows Forms you probably will need to write your own code to generate the controls for your data items.
Josh G