public class BerichtenOphalen
{
public List<Bericht> berichten = new List<Bericht>();
public List<Bericht> getBerichten(string email)
{
var client = new RestClient("http://localhost:8080/ewm/resources");
client.Authenticator = new HttpBasicAuthenticator("lode_vl@hotmail.com", "123456");
var request = new RestRequest("berichten/ontvanger/{id}", Method.GET);
request.AddUrlSegment("id", email);
List<Bericht> berichten = new List<Bericht>();
client.ExecuteAsync(request, response =>
{
if (response != null)
{
System.Diagnostics.Debug.WriteLine("not null" + response.Content.ToString());
this.berichten = JsonConvert.DeserializeObject<List<Bericht>>(response.Content);
System.Diagnostics.Debug.WriteLine("\n\n" +berichten.Count);
}
});
return berichten;
}
This class works, But i cant figure out how to return the List that is filled with objects.
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
BerichtenOphalen req = new BerichtenOphalen();
this.DataContext = req.getBerichten("lode_vl@hotmail.com");
base.OnNavigatedTo(e);
}
This is where i try to get my list to use as datacontext for my app, there is never any data in it.
Your code is currently broken - you've got two variables called berichten
, one of which is a local variable within the method, and one of which is an instance variable in the class.
You're returning the value of the local variable, but you're asynchronously populating the list referred to by the instance variable. That means your return value will always refer to an empty list, even after the asynchronous action has executed.
If you fix that bug, the list is still going to be empty when the method returns (because the data won't have been fetched yet) and there's nothing in List<T>
to help the UI notice when the collection has been updated. You could potentially use an ObservableCollection<>
, but you'd want to make sure that you only changed the collection on the UI thread.
If you're able to use C# 5, I would look into async
/await
to be honest - that will force your method to return a Task<List<string>>
but it'll indicate the asynchrony much more clearly. Your calling method would then look something like:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
BerichtenOphalen req = new BerichtenOphalen();
DataContext = await req.GetBerichtenAsync("lode_vl@hotmail.com");
base.OnNavigatedTo(e);
}
You might want to consider moving the Base.OnNavigatedTo(e)
method before the rest of the code though - or removing it entirely. Basically you need to think about what the original behaviour is, and whether you want that to occur immediately, or only after you've fetched the data.
See more on this question at Stackoverflow