0

here is part of my code:

public void refreshShowCase()
{

    for (int i = 0; i < 12; ++i)
    {
        bitmapImage[i] = new BitmapImage(new Uri(posterURLCollection[i]));
        image[i] = new Image { Source = bitmapImage[i] }; //Error occurs here****
    }
}

when I run this I get this error: The calling thread must be STA, because many UI components require this.

So I add my code inside Disapther.Invoke

this.Dispatcher.Invoke((Action)delegate
{
   BitmapImage[] bitmapImage = new BitmapImage[14];
   Image[] image = new Image[14];

   //Do a loop for defining Bitmaps sources
   for (int i = 0; i < 12; ++i)
   {
         bitmapImage[i] = new BitmapImage(new Uri(posterURLCollection[i]));
         image[i] = new Image { Source = bitmapImage[i] };
   }
}

Now I have this error: 'Dispatcher' doesn't exist in the current context!

How should I solve this? Please help.

Update1: mentioned code is inside void of a class which I have created!

  • Does System.Windows.Application.Current.Dispatcher.Invoke work? – Adam Sep 14 '18 at 15:34
  • @Adam: When I use that I get this: 'Current' does not exist in the type 'Application' – E. Mamaghani Sep 14 '18 at 15:37
  • You get a compile time error or a runtime ? – Soumen Mukherjee Sep 14 '18 at 15:40
  • @SoumenMukherjee: When I don't use Dispatcher I get runtime error which I have mentioned: The calling thread must be STA, because many UI components require this. But when I use Dispatcher a red line goes under the `This.Dispatcher` and says: 'Dispatcher' doesn't exist in the current context! – E. Mamaghani Sep 14 '18 at 15:44
  • My crystal ball says that you wrote a UWP app, not a WPF app. https://stackoverflow.com/questions/16477190/correct-way-to-get-the-coredispatcher-in-a-windows-store-app – Hans Passant Sep 14 '18 at 15:58
  • @HansPassant: In app's main class this.Dispatcher works fine! this problem is for that special class. – E. Mamaghani Sep 14 '18 at 16:10

1 Answers1

2

In your question, you are using this.Dispatcher.Invoke((Action)delegate inside of a custom class. this refers to functions inside of that class. Your custom class does not have Dispatcher.

Instead use: App.Current.Dispatcher.Invoke((Action)delegate and make sure this your custom class containing this code falls under your App namespace.

David Bentley
  • 824
  • 1
  • 8
  • 27