2010-12-09 98 views
0

我想爲我的WP7 Silverlight應用程序實現MVVM模式,並且遇到了異步JSON Rest調用的問題。我將我的WP7應用程序頁面中的以下兩種方法移到我的ViewModel類中。MVVM的異步JSON REST調用問題

public void FetchGames() 
{    

    ObservableCollection<Game> G = new ObservableCollection<Game>(); 
    //REST call in here 
    var webClient = new WebClient(); 
    Uri uri = new Uri("http://www.somewebsite.com/get/games/league/" + league); 
    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCompletedGames); 
    webClient.OpenReadAsync(uri); 
} 

private void OpenReadCompletedGames(object sender, OpenReadCompletedEventArgs e) 
{ 
    DataContractJsonSerializer ser = null; 
    ser = new DataContractJsonSerializer(typeof(ObservableCollection<Game>)); 
    Games = ser.ReadObject(e.Result) as ObservableCollection<Game>; 
    this.IsDataLoaded = true; 

} 

現在的問題是,因爲它是異步調用下面的代碼不起作用。以下代碼位於我的應用程序頁面上。

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
{ 
    base.OnNavigatedTo(e); 
    if (NavigationContext.QueryString.TryGetValue("league", out league)) 
    {    

try 
{ 
    App.gViewModel.league = league; 
    App.gViewModel.FetchGames(); 
    if(App.gViewModel.IsDataLoaded) 
    { 
    lbTeams.ItemsSource = App.gViewModel.Games; 
    }  
} 
catch() 
{     
    //error logging in here    
} 
    } 

} 

步進直通的代碼顯示了FetchGames被稱爲然後點擊下一行(如果(App.gViewModel.IsDataLoaded) )異步調用之前完成。所以IsDataLoaded永遠是假的,我不能綁定頁面上的列表框。

做了很多googleing我有一些可能的解決方案,但我無法將它們轉換爲我特別的問題。一個是這樣的,它與延續傳球風格相關「。我無法讓它工作,並會非常感謝一些幫助。

謝謝!

void DoSomethingAsync(Action<string> callback) { 
    HttpWebRequest req; // TODO: build your request 

    req.BeginGetResponse(result => { 
     // This anonymous function is a closure and has access 
     // to the containing (or enclosing) function. 
     var response = req.EndGetResponse(result); 

     // Get the result string and call the callback 
     string resultString = null; // TODO: read from the stream 

     callback(resultString); 
    }, null); 
} 

回答

3

這可以通過移動

lbTeams.ItemsSource = App.gViewModel.Games; 

到OpenReadCompletedGames方法結束來解決。您需要使用分派器從這裏更新UI。

Dispatcher.BeginInvoke(() => { lbTeams.ItemsSource = App.gViewModel.Games; }); 
+0

@你這次擊敗了我; o) – 2010-12-09 22:51:43