views:

312

answers:

3

Hi, In my WPF project there is a listbox in which I have to display images and next to each image their text (for example : date the photo was taken, location etc). I have tried creating a generic List but I still can't assign it to the listbox

Something like

Bscially I have been trying something on this lines.

public class LoadImages
{
    public static List<ImageLoader> LoadImages()
    {
        List<ImageLoader> img = new List<ImageLoader>();

        Uri uri = new Uri(@"http://somedomain.com/pic.jpg", UriKind.Absolute);
        BitmapImage bi = new BitmapImage(uri);

        img.Add(new ImageLoader("1_1",bi));

        return img;            
    }
}

public class ImageLoader
{
    string mediaid;
    BitmapImage thumbnail;

    public ImageLoader(string mediaid, BitmapImage b)
    {
        this.mediaid = mediaid;
        this.thumbnail = b;
    }
}

And my XAML looks like this.

        <ListBox Name="ListBox1" SelectionMode="Extended" ItemsSource="{Binding}"
             Width="300" Height="300" IsSynchronizedWithCurrentItem="True">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Image Source="{Binding thumbnail}"/>
                    <TextBlock Text="{Binding mediaid}"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

For the time being I have set the Window.DataContext

<Window.DataContext>
    <ObjectDataProvider ObjectType="{x:Type local:LoadImages}" MethodName="LoadImages"/>
</Window.DataContext>

But everytime I run the app the listbox shows up empty.

Any suggestions.

+1  A: 

Image element do support Uris for Source property. Why not making your LoadImages class return a set of Uris instead of images? Also image element can do async job for you ;)

Denis Vuyka
Thanks Dennis,Was missing the obvious :-)
Anand
Update : I changed my class and set the image element to bind to the string but the image still does not appear. Any pointers.
Anand
A: 

thumbnail and mediaid aren't public, and thus the binding fails.

wekempf
Hi,I tried setting it to public but still the binding fails.
Anand
A: 

After a lot of reading and googling I found my answer, all I had to do in the ImageLoader class is to create properties for mediaid and thumbnail and after that binding to the listbox now works like a char. So the ImageLoader class in asked in the question above now looks like

public class ImageLoader
{
    string mediaid;
    BitmapImage thumbnail;

    public string MediaId
    {
        get { return mediaid; }
        set { mediaid = value; }
    }

    public BitmapImage Thumbnail
    { 
        get { return thumbnail; } 
        set { thumbnail = value; } 
    }

    public ImageLoader(string mediaid, BitmapImage b)
    {
        this.mediaid = mediaid;
        this.thumbnail = b;
    }
}
Anand