我有一个带有 ObservableCollection、SaloonList 的 ViewModel,我用数据库中的数据填充它。当所有内容都在 ViewModel 文件中时,以下代码有效:
public MainViewModel()
{
PopulateList();
}
private void PopulateList()
{
WebClient webClient = new WebClient();
Uri site = new Uri(_URL);
UriBuilder uriBuilder = new UriBuilder(site);
uriBuilder.Path += String.Format("{0}", "all");
webClient.OpenReadCompleted += SaloonsCompleted;
webClient.OpenReadAsync(uriBuilder.Uri);
}
private void SaloonsCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null) { return; }
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DBSaloons));
DBSaloons jsonResponse = (DBSaloons)ser.ReadObject(e.Result);
this.SaloonList = jsonResponse.Results;
e.Result.Close();
}
但是,当我尝试从 ViewModel 中分离 PopulateList 方法并使用以下代码时,即使填充了操作中的列表并且在调试器窗口中打印了获取的轿车数量,我的 SaloonList 也不会被填充:
public MainViewModel()
{
Models.Fetcher fetch = new Fetcher();
fetch.PopulateList(this.SaloonList, onComplete);
}
Action<ObservableCollection<Saloon>, OpenReadCompletedEventArgs> onComplete = (ObservableCollection<Saloon> list, OpenReadCompletedEventArgs e) =>
{
if (e.Error != null) { Debug.WriteLine("Fetch Error"); return; }
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DBSaloons));
DBSaloons jsonResponse = (DBSaloons)ser.ReadObject(e.Result);
list = jsonResponse.Results;
e.Result.Close();
Debug.WriteLine("Fetched: " + list.Count.ToString() + " saloons");
};
这是该方法在 fetcher 类中的样子:
public void PopulateList(ObservableCollection<Saloon> list, Action<ObservableCollection<Saloon>, OpenReadCompletedEventArgs> onComplete)
{
Debug.WriteLine("Fetching...");
WebClient webClient = new WebClient();
Uri site = new Uri(_URL);
UriBuilder uriBuilder = new UriBuilder(site);
uriBuilder.Path += String.Format("{0}", "all");
webClient.OpenReadCompleted += (object sender, OpenReadCompletedEventArgs e) => onComplete(list, e);
webClient.OpenReadAsync(uriBuilder.Uri, list);
}
我究竟做错了什么?
编辑:
就这样解决了
public void PopulateList(Action<DBSaloons> callback, Action<Exception> exception)
{
Debug.WriteLine("Fetching...");
WebClient webClient = new WebClient();
Uri site = new Uri(_URL);
UriBuilder uriBuilder = new UriBuilder(site);
uriBuilder.Path += String.Format("{0}", "all");
webClient.OpenReadCompleted += ((sender, e) =>
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DBSaloons));
DBSaloons jsonResponse = (DBSaloons)ser.ReadObject(e.Result);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
if (e.Error == null) callback(jsonResponse);
else exception(e.Error);
});
e.Result.Close();
}
);
webClient.OpenReadAsync(uriBuilder.Uri);
}
然后在我的 ViewModel 中,我得到了这样的沙龙列表:
fetch.PopulateList( (list) =>
{
Debug.WriteLine("Fetched: " + list.Results.Count.ToString() + " saloons");
this.SaloonList = list.Results;
}, (exception) => { });