WPF - bind list to observable image collection

It should be very simple, but I can't get it to work ...

CustomItem is a class with the ThumbnailImage property. I'm trying to bind an ObservableCollection to a ListBox to display images. This is my code:

public ObservableCollection<CustomItem> AvailableItems { get; set; }

 <ListBox Width="103" Height="480" ItemsSource="{Binding AvailableItems}">
    <ListBox.ItemTemplate>
       <DataTemplate>
          <Border BorderBrush="Black" BorderThickness="1">
             <ContentControl Content="{Binding Path=ThumbnailImage}" 
                                             Width="100" Height="100" />
          </Border>
       </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

CustomItem is as follows

    public class CustomItem
        public Image ThumbnailImage { get; set; }
    }

Nothing appears in the ListBox at startup. Any idea what goes wrong? Thank!

- Change 1 - I assume that I can say that debugging is that closet.Items.Count == 0 when AvailableItems.Count == 5. I tried adding ItemsSource = "{Binding AvailableItems, UpdateSourceTrigger = PropertyChanged} ", but it did not help: (

- Change 2 -

I did the following in my XAML

DataContext="{Binding RelativeSource={RelativeSource Self}}" 

instead, when I did the following in code, everything worked:

DataContext = this;
+3
2

, , , -

  • ListBox DataContext, AvailableItems?
  • Image ?

BitmapImage source = new BitmapImage();
source.BeginInit();
source.UriSource = new Uri(yourUriString, UriKind.RelativeOrAbsolute);
source.EndInit();

ThumbnailImage = new Image();
ThumbnailImage.Source = source;

, ,
 http://www.mediafire.com/download.php?m99kv1uglrr31j9

, ,

+3

, :
1) ObservableCollection
2) DataContext ,
3) CustomItem ObservableCollection, INotifyPropertyChanged CustomItem.

, , :

    public MainWindow()
    {
        InitializeComponent();
        this.AvailableItems = new ObservableCollection<CustomItem>();
        Image i = new Image();
        BitmapImage src = new BitmapImage();
        src.BeginInit();
        src.UriSource = new Uri(@"C:\Users\Public\Pictures\Sample Pictures/Desert.jpg");
        src.EndInit();
        i.Source = src;
        i.Stretch = System.Windows.Media.Stretch.Fill;

        CustomItem ci = new CustomItem();
        ci.ThumbnailImage = i;

        this.AvailableItems.Add(ci);
    }


    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.DataContext = this;
    }
+3

All Articles