0

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.

Community
  • 1
  • 1
Stylzs05
  • 491
  • 2
  • 8
  • 19

1 Answers1

0

I figured it out and thought I would post my answer.

Here's what I did inside my foreach loop:

Uri uri = new Uri(imageFile.Fullname);
BitmapImage tmpImage = new BitmapImage(uri)
tmpImage.Freeze();
Action action = delegate { ListOfImages.Add(tmpImage); };
Dispatcher dispatcher = Dispatcher.CurrentDispatcher;
dispatcher.Invoke(action);

As you can see what I did was freeze the BitmapImage, and then delegated the action of adding the BitmapImage to the ListOfImages. Then at the end I invoked the action.

Stylzs05
  • 491
  • 2
  • 8
  • 19