将数据从JSON对象绑定到Hub部分内的ListView

时间:2016-03-16 10:21:42

标签: c# json listview windows-phone-8.1

我能够在反序列化后将数据从JSON成功绑定到listview,但是我无法绑定到Hub / HubSection内的相同列表视图。

使用ItemData.ItemsSource = obj;我能够将数据绑定到listview。当listview放在hubsection中时,如何绑定和显示数据?

我的MainPage.xaml中心代码

<Hub x:Name="MainHub" Header="My Hub">
        <HubSection x:Name="Test" Header="Online">
            <DataTemplate>
                <Grid>
         <ListView Name="ItemData">
         <ListView.ItemContainerStyle>
         <Style TargetType="ListViewItem">
         <Setter Property="HorizontalContentAlignment" Value="Stretch" />
         </Style>
         </ListView.ItemContainerStyle>
         <ListView.ItemTemplate>
         <DataTemplate>
         <Grid>
         <TextBlock Text="{Binding name}" FontSize="24"/>
         </Grid>
         </DataTemplate>
         </ListView.ItemTemplate>
         </ListView>
                </Grid>
            </DataTemplate>
        </HubSection>
    </Hub>

MainPage.xaml.cs中

public async void GetOnline()
    {
        Uri uri = new Uri("http://mywebsite.com");
        Dictionary<string, string> pairs = new Dictionary<string, string>();
        pairs.Add("id", CourseID.ToString());
        HttpClient client = new HttpClient();
        HttpFormUrlEncodedContent formContent = new    HttpFormUrlEncodedContent(pairs);
        HttpResponseMessage response = await client.PostAsync(uri,formContent);
        List<string> CName = new List<string>();
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();
            var obj = JsonConvert.DeserializeObject<List<RootObject>>(result);
            for (int i = 0; i < obj.LongCount(); i++)
            {
                CName.Add(obj[i].name);
            }
            //ItemData.ItemsSource = obj;
            //MainHub.DataContext = obj;
        }
    }

    public class RootObject
    {
        public int id { get; set; }
        public string name { get; set; }
    }

编辑1:

我现在能够检索数据。编辑XAML代码

 <Hub x:Name="MainHub" Header="My Hub">
 <HubSection x:Name="Test" Header="Online">
 <DataTemplate>
 <Grid>
 <ListView Name="ItemData"  ItemsSource="{Binding}"></ListView>
 </Grid>
 </DataTemplate>
 </HubSection>
 </Hub>

代码背后 -

 Test.DataContext = CName;

这是将数据绑定到集线器部分内的listview的正确方法吗?

1 个答案:

答案 0 :(得分:0)

删除hubsection的DataTemplate标签,然后它应该正常工作。