0

我编写了帮助类来从 Web 服务中检索数据以在 Silverlight 中使用:

   public static class RequestMethod
{
    public static string Get = "GET";
    public static string Post = "POST";


}
public static class RequestDataType
{
    public static string Xml = "Xml";
    public static string Json = "application/json";
}
public class HttpWebRequestHelper<T> 
{

    private readonly SynchronizationContext _context;


    private readonly ObservableCollection<T> _collection =
            new ObservableCollection<T>();
    public ObservableCollection<T> Collection
    {
        get { return _collection; }
    }

    public HttpWebRequestHelper()
    {
        _context = SynchronizationContext.Current;
    }

    public ObservableCollection<T> GetCollection ()
    {
        if (HttpWebRequest == null) throw new ArgumentNullException("request");
        HttpWebRequest.BeginGetResponse((result) =>
        {
            var response = HttpWebRequest.EndGetResponse(result);
            var stream = response.GetResponseStream();
            if (stream == null) return;
            var reader = new StreamReader(stream, Encoding.UTF8);
            var responseString = reader.ReadToEnd();
    var desirilizedObject = JsonConvert.DeserializeObject<IEnumerable<T>>(responseString);
            _context.Post((state) =>
                              {
                                  Collection.Clear();
                                  foreach (var item in desirilizedObject)
                                  {
                                      Collection.Add(item);
                                  }
                              }, null);
        }, null);
        return Collection;
    }

    private HttpWebRequest HttpWebRequest { get; set; }
    public void CreateRequest (string url,string requestMethod, string requestDataType)
  {

      var uri = new Uri(url, UriKind.Absolute);
        var request = (HttpWebRequest)WebRequest.Create(uri);
      request.Method = requestMethod;
      request.Accept = requestDataType;
      HttpWebRequest= request;
  }


}

这是我的班级的示例用法:

  var request = new HttpWebRequestHelper<DriverModel>();
        request.CreateRequest("http://localhost:11624/api/Drivers/", RequestMethod.Get, RequestDataType.Json);
       request.GetCollection();
       this.DataContext = request;

我想在 HttpWebRequest 完成时更新 UI。我怎样才能做到这一点 ?

4

1 回答 1

0

我想您在完成更改 UI 元素的请求时遇到了错误。例如,如果是这种情况,您应该加入当前线程;

Deployment.Current.Dispatcher.BeginInvoke(() => { this.Visibility = Visibility.Collapsed; });  
于 2012-11-05T12:39:08.543 回答