【问题标题】:DataBinding From Json in xaml?来自Xaml中Json的数据绑定?
【发布时间】:2013-01-26 19:24:21
【问题描述】:

我正在制作一个 WP7 应用程序并以 json 格式从我的 webapi 获取数据。我想知道如何进行数据绑定?我需要创建一个具体的类还是只使用 JArray?

[{"Id":"fe480d76-deac-47dd-af03-d5fd524f4086","Name":"SunFlower Seeds","Brand":"PC"}]

  JArray jsonObj = JArray.Parse(response.Content);
   this.listBox.ItemsSource = jsonObj;


        <ListBox x:Name="listBox" FontSize="26" Margin="0,67,0,0">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Id}" Width="100"/>
                        <TextBlock Text="{Binding Brand}" Width="100"/>
                        <TextBlock Text="{Binding Name}" Width="100"/>
                    </StackPanel>

                </DataTemplate>

            </ListBox.ItemTemplate>

        </ListBox>

【问题讨论】:

    标签: windows-phone-7 xaml data-binding json.net


    【解决方案1】:

    与 WPF 绑定时,需要使用属性。创建强类型对象,然后反序列化 JSON。

    创建你的对象:

    public class MyObject
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Brand { get; set; }
    }
    

    下面是一个非常松散的绑定示例,它基于您指示您将设置列表框的 ItemsSource 的方式:

    string json = "[{\"Id\":\"fe480d76-deac-47dd-af03-d5fd524f4086\",\"Name\":\"SunFlower Seeds\",\"Brand\":\"PC\"}]";
    
    var jsonObj = JArray.Parse( json );
    
    var myObjects = jsonObj.Select( x => JsonConvert.DeserializeObject<MyObject>( x.ToString() ) );
    
    this.listBox.ItemsSource = myObjects;
    

    注意:我没有使用过 json.net,因此可能有更好的方法来使用我发布的 json.net 反序列化数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2017-10-10
      • 1970-01-01
      相关资源
      最近更新 更多