我在我的Windows Phone 8应用程序中使用此代码,我从来没有从这种方法中获得回报:
private static ObservableCollection<Product> _productList = null;
public ObservableCollection<Product> GetProductList()
{
LoadProducts().Wait();
return _productList;
}
public Product GetProductById(int id)
{
return _productList.FirstOrDefault(p => p.Id == id);
}
private static async Task LoadProducts()
{
_productList = new ObservableCollection<Product>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:15017/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//HERE I NEVER GET THE RESPONSE
HttpResponseMessage response = await client.GetAsync("api/products").ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsAsync<List<Product>>();
foreach (var product in products)
{
_productList.Add(new Product(){Description = product.Description, Id=product.Id, Name = product.Name});
}
}
}
}
有人可以告诉我为什么会那样?我从我的ViewModel类运行此方法来加载数据
使用@Stephen Cleary sollution http://msdn.microsoft.com/en-us/magazine/dn605875.aspx存在一个问题:
在我的视图中,我设置了:
<ListBox Grid.Row="1" x:Name="listBox" ItemsSource="{Binding DataSource.Result}"
然后在codeBehind:
this.DataContext = new ProductViewModel();
然后在ProductViewModel中:
public AsyncTaskManager<ObservableCollection<Product>> DataSource { get; private set; }
和
this.DataSource = new AsyncTaskManager<ObservableCollection<Product>>(ProductRepository.LoadProducts());
在AsyncTaskManager中,PropertyChanged始终为null :(