So I'm building a WPF control that needs to load (and show) between 400 and 600 images (each one with size of 200Kb aprox.) from disk. The next is the codebehind for the control.
private List<BitmapImage> pages = new List<BitmapImage>();
private BackgroundWorker worker;
public PagesListBox()
{
InitializeComponent();
worker = new BackgroundWorker();
worker.WorkerSupportsCancellation = false;
worker.WorkerReportsProgress = false;
worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<BitmapImage> pagesList = new List<BitmapImage>();
var files = DirectoryServices.GetFiles(Properties.Settings.Default.PagesScanDirectory, new string[] { "*.tiff", "*.jpg", "*.png", "*.bmp" });
foreach (var file in files)
{
Uri uri = new Uri(file);
pagesList.Add(new BitmapImage(uri));
}
e.Result = pagesList;
}
void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
Pages.ItemsSource = (List<BitmapImage>)e.Result;
}
internal void LoadPages()
{
worker.RunWorkerAsync();
}
internal List<BitmapImage> AttachPages()
{
List<BitmapImage> attachedPages = new List<BitmapImage>();
foreach (BitmapImage eachItem in Pages.SelectedItems)
{
attachedPages.Add(eachItem);
pages.Remove(eachItem);
}
Pages.ItemsSource = null;
Pages.ItemsSource = pages;
return attachedPages;
}
I try to assign the pages list to the view (wich I can not using the background worker), but It fails.
Is ther any other way to load the images asynchronously (maybe updating the UI) or this approach of Background Worker I'm trying is fine. And, if it's fine, how can I solve the exception (within completed event):
Must create DependencySource on same Thread as the DependencyObject.
Thanks