在UWP问题中将JSON JArray绑定到Listview

时间:2017-01-20 17:56:14

标签: c# json listview uwp win-universal-app

在visual studio通用Windows应用程序中,我正在尝试将JArray绑定到Listview。似乎编译正常,行数填充到Listview中,但没有数据填充行。我在这里做错了什么,或者这甚至可能吗?

使用Newtonsoft.Json.Linq;

XAML

<ListView Grid.Row="0" x:Name="lstJobData">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Margin="8">
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>
                <TextBlock Grid.Row="0" Text="{Binding Path=job_id}" FontSize="14" Foreground="White"/>
                <TextBlock Grid.Row="1" Text="{Binding Path=job_number}" FontSize="14" Foreground="White"/>
                <TextBlock Grid.Row="2" Text="{Binding Path=ship_type}" FontSize="14" Foreground="White"/>        
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

来自服务层的JArray(从Json字符串转换为Jarray)

{[
  { "job_id": 399783, "job_number": "XYZ-J111111", "ship_type": "c" },
  { "job_id": 445672, "job_number": "XYZ-J222222", "ship_type": "p" },
  { "job_id": 896543, "job_number": "XYZ-J333333", "ship_type": "f" }
]}

XAML(代码背后)

private async void Button1_Click(object sender, RoutedEventArgs e)
{
    MyServices.Service1Client client = new MyServices.Service1Client();
    var itemSource = await client.GetDTAsync();
    JArray result = JArray.Parse(itemSource);

    lstJobData.ItemsSource = result;

}

1 个答案:

答案 0 :(得分:0)

当我们将JArray设置为ItemsSource的{​​{1}}属性时,我们无法使用XAML中的路径。路径表示Property-path,它将指向项目的属性。此外,项目中没有ListView属性。

如果要在XAML中使用路径,我们应该能够创建job_id类。在Job中,我们应该能够定义Jobjob_idjob_number属性。 然后,我们应该能够将ship_type添加到Job类的ObservableCollection

例如:

Job

背后的代码:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Button HorizontalAlignment="Right" VerticalAlignment="Top" Click="Button1_Click" >click</Button>
    <ListView VerticalAlignment="Bottom" HorizontalAlignment="Center" Grid.Row="0" x:Name="lstJobData">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid Margin="8">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
                    <TextBlock Grid.Row="0" Text="{Binding Path=job_id}" FontSize="14" Foreground="Red" />
                    <TextBlock Grid.Row="1" Text="{Binding Path=job_number}" FontSize="14" Foreground="Red" />
                    <TextBlock Grid.Row="2" Text="{Binding Path=ship_type}" FontSize="14" Foreground="Red" />
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</Grid>