Mega Code Archive
Updating the UI from a Background Thread
//File: Page.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
namespace SilverlightApplication3
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
private void RetrieveXMLandLoad_Click(object sender, RoutedEventArgs e)
{
Uri location = new Uri("http://localhost:9090/Books.xml", UriKind.Absolute);
WebRequest request = HttpWebRequest.Create(location);
request.BeginGetResponse(new AsyncCallback(this.RetrieveXmlCompleted), request);
}
void RetrieveXmlCompleted(IAsyncResult ar)
{
List bookList;
HttpWebRequest request = ar.AsyncState as HttpWebRequest;
WebResponse response = request.EndGetResponse(ar);
Stream responseStream = response.GetResponseStream();
using (StreamReader streamreader = new StreamReader(responseStream))
{
XDocument xDoc = XDocument.Load(streamreader);
bookList = (from b in xDoc.Descendants("Book")
select new Book()
{
Author = b.Element("Author").Value,
Title = b.Element("Title").Value,
PublishedDate = Convert.ToDateTime(b.Element("DatePublished").Value),
NumberOfPages = b.Element("NumPages").Value,
ID = b.Element("ID").Value
}).ToList();
}
Dispatcher.BeginInvoke(() => DataBindListBox(bookList));
}
void DataBindListBox(List list)
{
BooksListBox.ItemsSource = list;
}
}
public class Book
{
public string Author { get; set; }
public string Title { get; set; }
public string ISBN { get; set; }
public string Description { get; set; }
public DateTime PublishedDate { get; set; }
public string NumberOfPages { get; set; }
public string Price { get; set; }
public string ID { get; set; }
}
}