Windows Phone 8中ListBox的数据绑定

本文关键字:数据绑定 ListBox Phone Windows | 更新日期: 2023-09-27 17:50:30

我是Windows Phone 8的新手。我有一个来自服务器的数据列表,格式如下:

RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
  mylist.ItemsSource = json.friends;
public class Friend
{
    public string first_name { get; set; }
    public string last_name { get; set; }
    public string place { get; set; }
    public string going { get; set; }
    public string thumbnail { get; set; }
}
    public class RootObject
    {
        public List<Friend> friends { get; set; }
    }

我想在UI中的ListBox中显示该数据:

  <ListBox x:Name="mylist" Margin="10,0,30,0" Height="486" Width="404" FontSize="20">
            <ListBox.ItemTemplate>
                <DataTemplate >
                    <StackPanel Margin="10,0,10,8">
                        <TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding last_name }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding place }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding going }" TextWrapping="Wrap" FontSize="18" />
                        <TextBlock Text="{Binding thumbnail }" TextWrapping="Wrap" FontSize="18" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

Windows Phone 8中ListBox的数据绑定

ListBox上的ItemsSource应绑定到friends上,如下所示:

<ListBox ItemsSource="{Binding friends}"  Margin="10,0,30,0" Height="486" Width="404" FontSize="20">
    <ListBox.ItemTemplate>
        <DataTemplate >
            <StackPanel Margin="10,0,10,8">
                <TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="18" />
                <TextBlock Text="{Binding first_name }" TextWrapping="Wrap" FontSize="24" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

如果你还没有这样做的话,你需要在下载数据后为页面设置DataContext,就像这样(假设你在页面的代码后文件中进行下载,例如mainpage . example .cs):

RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
this.DataContext = json;