I am using a ListView in WPF to display some images, which is done by filling up an ObservableCollection with Image objects and setting that list as ItemsSource. My implementation is shown here:
public partial class MainWindow : Window
{
public ObservableCollection<Image> imageList;
public MainWindow()
{
InitializeComponent();
imageList = new ObservableCollection<Image>();
ImageView.ItemsSource = imageList;
}
private void loadImages(object sender, RoutedEventArgs e)
{
List<string> filePaths = Directory.GetFiles(@"C:\SomeImages")
foreach (string filePath in filePaths)
{
Image image = new Image();
BitmapImage bimage = new BitmapImage();
bimage.BeginInit();
bimage.UriSource = new Uri(filePath, UriKind.Absolute);
bimage.EndInit();
image.Source = bimage;
imageList.Add(image);
}
}
}
My intention was for the UI to update once every iteration of the foreach loop as the observable list is filling up. However the foreach loops fills up the list completely before returning control to UI, which then shows all the pictures at the same time. This lags out the program for several seconds as there are around 100 pictures.
Is there any way i can make the program update the UI one element at a time, and possibly also keep UI responsive?