I have a method that populates a List with 5 random images. The method returns correctly. When I call the method to populate the List before this.InitializeComponent();
in the codebehind, the images appear on screen. However, when I call the method afterwards, it has no effect on what is shown on screen. What can I do to fix this? It seems like I need to call RaisePropertyChanged()
or something along these lines, but I can't find a way to do this. Can anyone please help ?
In my code behind I have the code :
public List<BitmapImage> listOfImages { get; set; }
private async void Get_Images(object sender, RoutedEventArgs e)
{
//code to get 5 random images
IReadOnlyList<StorageFile> fileList = await query.GetFilesAsync();
listOfImages = new List<BitmapImage>();
foreach (StorageFile file in fileList)
{
BitmapImage src = new BitmapImage();
src.SetSource(await file.OpenAsync(FileAccessMode.Read));
listOfRelatedImages.Add(src);
}
}
And in my XAML :
<ItemsControl ItemsSource="{Binding Path=listOfImages}" HorizontalContentAlignment="Stretch">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel VerticalAlignment="Center">
<Image x:Name="images" Source="{Binding}" Visibility="Visible" Stretch="Fill">
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Use ObservableCollection instead of List
ItemsControl track collection changes(add/remove/reset/move) with INotifyCollectionChanged interface, so if you want ItemsControl to update automatically, you need to implement this interface on the list. WPF already contains generic collection that implement this interface.
Replace
List<BitmapImage> listOfImages
With
ObservableCollection<BitmapImage> listOfImages
And it should work