To begin with, reading the file system must necessarily occur in a separate thread or via async / await. Numerous examples on the Internet are wrong with reading data in the main stream (and almost in OnClick
).
First, separate the UI and logic. In UI, simply bind to ObservableCollection<ImageVM>
, and calmly load pictures in the background.
For the VM part, the collection is empty for starters. Go to the separate thread-pool-stream directory:
var imageFiles = await Task.Run(() => Directory.GetFiles(dir, "*.jpg")); foreach (var f in imageFiles) { BitmapImage img = await Task.Run(() => LoadImage(f)); ImageVM imageVM = new ImageVM(img); ImageCollection.Add(imageVM); }
Here, the LoadImage
code must load a picture asynchronously or create a thumbnail. For example (this is without a size check):
BitmapImage LoadImage(string path) { BitmapImage s = new BitmapImage(); s.BeginInit(); s.UriSource = new Uri(Path.GetFullPath(path)); s.CacheOption = BitmapCacheOption.OnLoad; s.EndInit(); s.Freeze(); return s; }
If there are many pictures, and the list itself does not “fly” after downloading, use virtualization .
An alternative solution may be to use PriorityBinding
.