2011-08-12 68 views
0

我試圖使用web服務讀取數據並將其顯示在如下所示的成本低廉的lisBox上,但它沒有工作。 「當我做調試我的手機應用程序屏幕不顯示任何列表」將webService數據綁定到ListBox DataTemplate WP7

XAML代碼:

<ListBox Height="500" HorizontalAlignment="Left" 
     Margin="8,47,0,0" 
     Name="friendsBox" VerticalAlignment="Top" Width="440"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <StackPanel Orientation="Horizontal"> 
       <Image Height="100" Width="100" 
         VerticalAlignment="Top" Margin="0,10,8,0" 
         Source="{Binding Photo}"/> 
       <StackPanel Orientation="Vertical"> 
        <TextBlock Text="{Binding Nom}" FontSize="28" TextWrapping="Wrap" Style="{StaticResource PhoneTextAccentStyle}"/> 
        <TextBlock /> 
       </StackPanel> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

C#代碼:

void friends_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
{ 
    if (e.Error == null) 
    { 
     ListBoxItem areaItem = null; 
     StringReader stream = new StringReader(e.Result); 
     XmlReader reader = XmlReader.Create(stream); 

     string Nom = String.Empty; 
     string Photo = String.Empty; 

     while (reader.Read()) 
     { 
      if (reader.NodeType == XmlNodeType.Element) 
      { 

       if (reader.Name == "nom") 
       { 

        Nom = reader.ReadElementContentAsString(); 

        areaItem = new ListBoxItem(); 
        areaItem.Content = Nom; 
        friendsBox.Items.Add(Nom); 
       } 
       if (reader.Name == "photo") 
       { 

        Photo = reader.ReadElementContentAsString(); 

        areaItem = new ListBoxItem(); 
        areaItem.Content = Photo; 
        friendsBox.Items.Add(Photo); 
       } 
      } 
     } 
    } 
} 
+1

剛纔你的問題是什麼?你需要更加詳細?它在哪裏失敗?什麼是錯誤/異常? – ColinE

回答

5

的問題是關係到不一致的方式,你」重新管理你的數據。 XAML中的數據綁定語法與您在代碼隱藏中手動加載項目的方式不匹配。沒有看到你的XML的結構,我會推斷你試圖在列表框中顯示的每個項目都有兩個屬性 - nom和photo。如果是這樣的話,你可以輕鬆解決您在用以下替換您的代碼隱藏代碼遇到的問題:

// create this additional class to hold the binding data 
public class ViewData 
{ 
    public string Nom { get; set; } 
    public string Photo { get; set; } 
} 

void friends_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
{ 
    if (e.Error == null) 
    { 
     var doc = XDocument.Load(new StringReader(e.Result)); 
     var items = from item in doc.Element("data").Elements("item") 
        select new ViewData 
        { 
         Nom = item.Element("nom").Value, 
         Photo = item.Element("photo").Value, 
        }; 
     friendsBox.ItemsSource = items; 
    } 
} 

你將需要添加到System.Xml.Linq的一個參考,並添加適當的使用聲明到您的代碼。

HTH!

Chris

+0

謝謝@Chris Koenig,它終於奏效了! – MarTech

相關問題