chobo2
chobo2

Reputation: 85765

DataBinding From Json in xaml?

I am making a WP7 app and getting data back from my webapi as json. I am wondering how can I databind it? Do I need to make a concrete class or can I just use 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>

Upvotes: 0

Views: 1142

Answers (1)

Metro Smurf
Metro Smurf

Reputation: 38335

When binding with WPF, you need to use Properties. Create a strongly typed object and then deserialize the JSON.

Create your object:

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

And here is a very loose example of binding based on how you've indicated you'll be setting the ItemsSource of the list box:

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;

Note: I've not used json.net, so there may be a better way to deserialize an array with json.net that what I've posted.

Upvotes: 1

Related Questions