Question

I have a single ListBox that is supposed to display a picture with each item. I wrote codes and when I run it, pictures couldn't be displayed, but only text displayed. What have I done wrong in my codes? I made sure the image file path is correct.

I want to display each item with text (right side) and icon (left side).

WPF:

<ListBox Name="ListTest" DisplayMemberPath="Name"  HorizontalAlignment="Left" Height="358" Margin="603,38,0,0" VerticalAlignment="Top" Width="361">
</ListBox>

C#

public partial class UserControl2 : UserControl
{
    public UserControl2()
    {
        InitializeComponent();
        this.LoadLogos();
    }

    private void LoadLogos()
    {
        this.ListTest.Items.Add(new CompanyDataContext("Adobe", "Adobe is a designing tool.", "/Company Logos/testDinner.jpg"));
        this.ListTest.Items.Add(new CompanyDataContext("Facebook", "FedEx is a social networking website.", "/Company Logos/facebook.jpg"));
        this.ListTest.Items.Add(new CompanyDataContext("FedEx", "FedEx is a courier company.", "/Company Logos/fedex.jpg"));

    }

    private class CompanyDataContext
    {
        public CompanyDataContext(string name, string about, string image)
        {
            this.Name = name;
            this.About = about;
            this.Image = image;
        }

        public string Name { get; private set; }
        public string About { get; private set; }
        public string Image { get; private set; }
    }
}
Was it helpful?

Solution

You need a DataTemplate for CompanyDataContext as it does not inherit from Visual, WPF has no idea how to render it hence it calls the ToString Method on this.

This can be dealt with aDataTemplate for the ListBox

Untested template:

<ListBox.ItemTemplate>
            <DataTemplate>
                <Border x:Name="bord" CornerRadius="5" Margin="2" BorderBrush="LightGray" BorderThickness="3" Background="DarkGray">
                    <StackPanel Margin="5">
                        <TextBlock x:Name="txt" Text="{Binding Name}" FontWeight="Bold"/>
                        <Image Source="{Binding Image}" Height="100"/>
                    </StackPanel>
                </Border>

            </DataTemplate>
</ListBox.ItemTemplate>

Edited typo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top