BrunoLM
BrunoLM

Reputation: 100371

How to populate a ListBox with external API response?

I am making a request to an API, the only option I get is async get response

var r = (HttpWebRequest)WebRequest.Create(url);
r.BeginGetResponse(new AsyncCallback(ResponseMethod), state);

So, I built everything I need to get the data, and it is working. But the data is received in a different thread. My ListBox is bound to StreamItems that exists in my MainViewModel.

public ObservableCollection<StreamItemViewModel> StreamItems { get; private set; }

But I am in a different thread, so I cannot directly access this property to add new values to it. When I try:

StreamItems.Add(new StreamItemViewModel
{
    Content = responseContent
});

I get:

UnauthorizedAccessException - Invalid cross-thread access.

How can I add values that I got from the request?

Upvotes: 1

Views: 355

Answers (1)

BrokenGlass
BrokenGlass

Reputation: 160982

You have to do this on the UI thread - for that you can use Dispatcher.BeginInvoke():

Dispatcher.BeginInvoke(() =>
{
  StreamItems.Add(new StreamItemViewModel
  {
      Content = responseContent
  });
});

Upvotes: 3

Related Questions