I want to merge between my code that contains the Web service and the code of WindowsPhoneDataBound Applica开发者_运维知识库tion.Is it possible? and how? My Code:
private void button1_Click(object sender, RoutedEventArgs e)
{
Uri url = new Uri("http://www.google.com/ig/api?weather=" + textBoxVille.Text, UriKind.Absolute);
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(url);
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
StringReader stream = new StringReader(e.Result);
XmlReader reader = XmlReader.Create(stream);
reader.MoveToContent();
while (reader.Read())
{
switch (reader.Name)
{
case ("day_of_week"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
} break;
case ("low"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
} break;
case ("high"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
} break;
case ("icon"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
} break;
case ("condition"):
{
listBox1.Items.Add(new ListBoxItem()
{
Content = reader.GetAttribute("data")
});
} break;
case ("weather"):
break;
}
}
reader.Close();
}
}
Of course it is possible with the help of data binding and observable collections. Instead of adding new list box items every time you get a new element, you can use an ObservableCollection. Set the data source of the listbox to the observable collection.
The benefit of using ObservableCollection is that whenever you add or remove an element from your collection, your listbox will automatically reflect that. So no need to manually add or remove listboxItems. If your listboxItem has custom layout, then you can create a dataTemplate and bind data to the elements which needs to be displayed in the listboxItem.
精彩评论