【发布时间】:2010-10-02 14:40:09
【问题描述】:
我今天一直在尝试使用 WP7 应用程序,但遇到了一些困难。 我喜欢将 UI 和主应用代码分开,但我碰壁了。
我已经成功实现了一个 webclient 请求并得到了结果,但是由于调用是异步的,我不知道如何将此备份传递到 UI 级别。我似乎无法等待响应完成或任何事情。 我一定是做错了什么。
(这是我在我的网站上下载的 xbox360Voice 库:http://www.jamesstuddart.co.uk/Projects/ASP.Net/Xbox_Feeds/,我将其移植到 WP7 作为测试)
这里是后端代码sn-p:
internal const string BaseUrlFormat = "http://www.360voice.com/api/gamertag-profile.asp?tag={0}";
internal static string ResponseXml { get; set; }
internal static WebClient Client = new WebClient();
public static XboxGamer? GetGamer(string gamerTag)
{
var url = string.Format(BaseUrlFormat, gamerTag);
var response = GetResponse(url, null, null);
return SerializeResponse(response);
}
internal static XboxGamer? SerializeResponse(string response)
{
if (string.IsNullOrEmpty(response))
{
return null;
}
var tempGamer = new XboxGamer();
var gamer = (XboxGamer)SerializationMethods.Deserialize(tempGamer, response);
return gamer;
}
internal static string GetResponse(string url, string userName, string password)
{
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
Client.Credentials = new NetworkCredential(userName, password);
}
try
{
Client.DownloadStringCompleted += ClientDownloadStringCompleted;
Client.DownloadStringAsync(new Uri(url));
return ResponseXml;
}
catch (Exception ex)
{
return null;
}
}
internal static void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
ResponseXml = e.Result;
}
}
这是前端代码:
public void GetGamerDetails()
{
var xboxManager = XboxFactory.GetXboxManager("DarkV1p3r");
var xboxGamer = xboxManager.GetGamer();
if (xboxGamer.HasValue)
{
var profile = xboxGamer.Value.Profile[0];
imgAvatar.Source = new BitmapImage(new Uri(profile.ProfilePictureMiniUrl));
txtUserName.Text = profile.GamerTag;
txtGamerScore.Text = int.Parse(profile.GamerScore).ToString("G 0,000");
txtZone.Text = profile.PlayerZone;
}
else
{
txtUserName.Text = "Failed to load data";
}
}
现在我知道我需要在 ClientDownloadStringCompleted 中放置一些东西,但我不确定是什么。
【问题讨论】:
标签: asynchronous windows-phone-7