So, I have been working on adding BitmapImages to a ListBox for pretty much my whole work day. Here's my code:
public class SomeClassViewModel : ViewModelBase
{
public SomeClassViewModel(EnhanceImage image)
{
LoadImages();
}
public List<BitmapImage> ListOfImages { get; set; }
public void LoadImages()
{
ListOfImages = new List<BitmapImage>();
DirectoryInfo imageDir = new DirectoryInfo(@"..\..\Images");
foreach (FileInfo imageFile in imageDir.GetFiles("*.jpg"))
{
Uri uri = new Uri(imageFile.FullName);
ListOfImages.Add(new BitmapImage(uri));
}
}
}
As you can see I'm adding all the images in the folder "Images" that have the file extension ".jpg" into a list of BitmapImages called ListOfImages. Then after that I bind it to a ListBox in the XAML like so:
<ListBox ItemsSource="{Binding ListOfImages}"/>
The problem is is that when I run it, I get this error: "the calling thread cannot access this object because a different thread owns it". Now I kind of know what I have to do from looking at this StackOverflow thread: The calling thread cannot access this object because a different thread owns it.How do i edit the image?, but I just couldn't follow it. Could someone show me how to use this Dispatcher.Invoke?
EDIT: Right now I'm just trying to get the URI of the image to show up in a list.