将Web服务数据绑定到ListBox DataTemplate WP7

时间:2011-08-12 09:43:28

标签: web-services data-binding windows-phone-7 listboxitems

我正在尝试使用Web服务读取数据并将其显示在一个已经过滤的lisBox上,如下所示,但它不起作用。 “当我进行调试时,我的手机应用程序屏幕没有显示任何列表”

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 个答案:

答案 0 :(得分:5)

问题与您管理数据的方式不一致有关。 XAML中的数据绑定语法与您在代码隐藏中手动加载项的方式不匹配。在没有看到XML结构的情况下,我将推断出您尝试在ListBox中显示的每个项目都有两个属性 - 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的引用,并在代码中添加相应的using语句。

HTH!

克里斯

相关问题