2011-08-12 14 views
0

Webサービスを使用してデータを読み込み、以下のようにそれを表示しようとしていますが、動作しませんでした。WebサービスデータをListBoxにバインドするDataTemplate WP7

<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コード「私はデバッグを行うと自分の携帯電話のアプリケーション画面には、任意のリストが表示されません」あなたのデータを再管理する。 XAMLのデータバインディング構文は、コードビハインド内のアイテムを手動でロードする方法と一致しません。 XMLの構造を見ることなく、ListBoxに表示しようとしている各アイテムにnomとphotoの2つのプロパティがあると推測します。そのような場合は、簡単に次のようにあなたの分離コード内のコードを置き換えることによって、あなたは経験している問題を解決することができます

// 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への参照を追加し、追加する必要がありますコードに適切なusingステートメントを追加します。

HTH!

クリス

+0

ありがとう@クリスKoenig、それは最終的に働いた! – MarTech

関連する問題