Page.xmal.cs 页面

 public partial class Page : UserControl
    {
        public Page()
        {
            InitializeComponent();
        }
        private SynchronizationContext syncContext;
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            Uri endpoint = new Uri("http://localhost:4104/Handler1.ashx");
            syncContext = SynchronizationContext.Current;//得到当前线程

            WebRequest request = WebRequest.Create(endpoint);
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.BeginGetResponse(new AsyncCallback(ResponseReady), request);


        } 
        void ResponseReady(IAsyncResult asyncResult)
        {
            WebRequest request = asyncResult.AsyncState as WebRequest;
            WebResponse response = request.EndGetResponse(asyncResult);
            if (response != null)
            {
                syncContext.Post(aaa, response);//抛出线程,如果不抛出去,将还会处于原来线程上,无法对UI界面上的listBox 进行数据绑定

                                                      //
            }         

        }
        private void aaa(object state)
        {
            WebResponse response = state as WebResponse;

             using (Stream responseStream = response.GetResponseStream())
             {
                 DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Blog));

                 Blog blogs = jsonSerializer.ReadObject(responseStream) as Blog;   //进行反序列化          
                 Posts.ItemsSource = blogs.Posts;//数据绑定,Posts是一个listbox
                 int s = Posts.SelectedIndex;
             }
        
        }

   }

handler。ashx页面

 

    public class Handler1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            List<Post> posts = new List<Post>()
        {
            new Post{ Id=1, Title="一步一步学Silverlight 2系列(13):数据与通信之WebRequest", Author="slb" },
            new Post{ Id=2, Title="一步一步学Silverlight 2系列(12):数据与通信之WebClient", Author="slb" },
            new Post{ Id=3, Title="一步一步学Silverlight 2系列(11):数据绑定", Author="slb" },
            new Post{ Id=4, Title="一步一步学Silverlight 2系列(10):使用用户控件", Author="slb" },
            new Post{ Id=5, Title="一步一步学Silverlight 2系列(9):使用控件模板", Author="slb" },
            new Post{ Id=6, Title="一步一步学Silverlight 2系列(8):使用样式封装控件观感", Author="slb" }
        };

            Blog blog = new Blog();
            blog.Posts = posts;

            context.Response.Write(JavaScriptConvert.SerializeObject(blog));//序列化,响应到客户端从服务器。

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

 

 

 

Posted on 2008-09-11 17:55  sunlibo  阅读(150)  评论(0)    收藏  举报