Binding JSON data to a LongListSelector

Pre requisite (Part 1) of this article was published here: Deserialize Json data using Newtonsoft Json.NET library

If you have successfully parsed your JSON data from a local/hosted file or read data from a server, now you need to show it to the user. To do use we use the concept of DataBinding.

What is DataBinding?

According to MSDN, Data binding is the process that establishes a connection between the application UI and business logic. If the binding has the correct settings and the data provides the proper notifications, then, when the data changes its value, the elements that are bound to the data reflect changes automatically. Data binding can also mean that if an outer representation of the data in an element changes, then the underlying data can be automatically updated to reflect the change. For example, if the user edits the value in a TextBox element, the underlying data value is automatically updated to reflect that change.

Now let’s see a practical example to show this feature. We will continue with the app from previous post – Deserialize Json data using Newtonsoft Json.NET library


 

1. a. Creating a template

The first step is to create a general template to show the data. Let’s take a look at our sample JSON dat
a used in the app. Now for a simple template, let’s assume we need to show all 5 types of information form the Json data. Let’s create a StackPanel for each information tag like this.
This results in the following format:SP1

1. b. Creating a Template

Let’s use the same style for all the tags and create a unified StackPanel containing 5 such smaller StackPanel.This is what our template looks like now:

SP2

2. Creating a LongListSelector with a DataTemplate

Now we need to show multiple objects from the JSON, we will create a LongListSelector and provide it with a DataTemplate (which the above StackPanel we created!) to show our JSON. The following code does the magic:
The result looks like a empty StackPanel but don’t worry everything is still there and it’s fine.

3. DataBinding

This the important step. We need to careful to bind correct elements to correct UI elements.  We need to bind the LongListSelector with the name of object in RootObject class. Our classes are these:
Thus we need to bind, LongListSelector with mydata from line 12. Please be careful as to make sure to bind the RootObject with the LongListSelector. And then we bind the various tags like id, name, location etc to respective variable of class mydataYou can see the binding syntax from the code snippet below:
Please take a moment to observe various Data Bindings carefully before proceeding.

4. Set the DataContext of LongListerSelector to parsed JSON

This is the final step. After parsing the JSON data, set the DataContext of LongListSelector to your parsed JSON data like:

Feel free to be creative with the DataTemplate you create. You can now use this knowledge to download Json files from servers to create a dynamic app, use some web APIs to exchange Json data and make an awesome app.

And you’re done! This is what final result looks like:

wp_ss_20150304_0004

 

 

 

 

 

 

 

 

 

 

 

Download source code from Github

 

Visit my personal website chauhanvaibhav.net

Parsing and displaying simple XML feeds in Windows Phone 8 app

This post will explain how you could parse remotely located XML feeds and display content in Windows Phone 8 app. Here’s an sample XML file which we plan to fetch and display as a list in our app. If you are not familiar with XMLs then you could refer to some basic tutorials on w3schools.com. Here are few things worth remembering..

  • With XML, your data can be available to all kinds of reading machines
  • You can define any tag in XML, taking care of the fact that each tag opened should be closed
  • You can have any level of nesting of tags in XML
  • XML tags are case sensitive
  • In XML, all elements must be properly nested within each other
  • XML documents must contain one element that is the parent of all other elements.
  • In XML, the attribute values must always be quoted.

If you have a database on some server, you can easily create a web service for it and use the web service to get content for your app. This is useful when you already have things setup for your website and want to take it to mobile with native apps. Also if you have an app on one platform its easier to develop it for another using the same web services. It keeps your data synced and frees you from worrying about data inconsistency.

Here’s the PHP code which I used to generate the sample XML file. I fetch the rows from MySQL database and echo it within properly nested tags. You could pass GET/POST requests to filter the data which you want to return. For example, you may choose to display only authors with count greater than 20.

Now lets jump into building the app.

Step 1. Add a class Author to store the data for an author

In this tutorial we are fetching all the authors from a XML file. So we name our class Author which will store an author’s data.
Step 2. Add a list `authors` which will have items of type Author

Below the class Author add a list authors to store all the authors details



1

Step 3. Call a webclient on LayoutRoot_Loaded event to fetch the XML file

2

Add a loaded event handler for MainPage.xaml‘s LayoutRoot and add the code below to make a call to a WebClient and fetch the XML file.

  • We create a new instance of WebClient class
  • Invoke its OpenReadAsync function and specify the URL for your XML file
  • OpenReadCompleted calls client_OpenReadCompleted when the XML file at the specified URL has been downloaded
  • client_OpenReadCompleted has the code to parse the XML

 

 

Step 4. Parse the XML and store the data in the list `authors`

We earlier created a list `authors` to store the details of all the authors. We will use it now while parsing the XML.

  • The downloaded stream e.Result is stored in a Stream variable str
  • Next we create an instance of XDocument class and load the stream str in it and name it loadedData
  • We then iterate through all the descendants of the node author using a foreach loop
  • For each author we create a new instance of our class Author and add the values to it
  • We then add this Author object to our list `authors`
  • Finally we set the ItemSource of our ListBox to the list `authors`

authorlistbox.ItemsSource = authors;

Step 5. Create a Listbox to display all the authors using XAML

This ListBox will display the names of all the authors fetched from the XML file

  • We define the data template of the ListBox and a TextBlock to it
  • We bind the TextBlock with name. It is the same name which we used in our class Author
  • Give the ListBox some name, here we use authorlistbox

 

That’s all you need to do. Try deploying the app in the emulator and see how it works.

3

 

Suppose you have the XML stored locally in your app. Then you could use the following code to parse and display it.

Now that you have successfully displayed the content in a list box, lets try showing the count on ListBox_Selection_Changed. Most of the tutorials skipped this and I used to get struck here 😛
Get the full project source code here
Download full project source code XML-Parsing.zip

How to work with ListBox selected item in Windows phone application

In this post I am going to talk about different techniques of accessing a Listbox Selected item.

When we populate a Listbox with data items we have two options

1. First is that we can use Listbox items directly

2. Second we can make the use of databinding.

 

When we use option 1 the Selected item is usually the Listbox item so we can access it easily and perform the desired manipulations on it.

But when we make use of Second option which is the most widely used option the SelectedItem is the type of the business object (data class) which we use when performing data binding

There are different methods of accessing the ListBox Selected item which will be explained below with the help of an example.

 

In the following example I shall be creating a Listbox of student names along with a button which shall display their marks along with their name in a Texblock given below the List.

The different steps that need to be followed are

 

1. Create a new project Listboxselecteditem.

2. Then open the MainPage.xaml and remove the XAML code for the StackPannel named TitlePanel and replace it with the following code so as to change the page name and application name .

 


 

 

3. Now add the following Xaml code in the Grid named ContentPanel so as to create a list box in the page having the name mylistbox and bind the target Textblock nameblock  with data source name property. It also adds two Textblocks having the name Studentnameblock and marksblock to display the name and marks of selected student.

 



 

4. Now open the page MainPage.xaml.cs.

5. Create a public class called Resultclass having the properties name and marks in the page globally.


 

6. Then add the following code consisting of two global arrays for sample data to be used inside listbox named mylistbox

 

7. After that make a sample list from the data given above with the help of the following code given below.

 


 


 

8. Then call the function makeasamplelist in the constructor of the MainPage.xaml.cs.

 


 

If you face any problems while understanding the above code you can refer to the following blog post to understand the basics of data binding.

http://www.windowsapptutorials.com/windows-phone/data-binding-in-windows-phone-app-one-way-binding/

 

9. Now to add the following code for the Listbox SelectionChanged Event handler in the MainPage.xaml.cs.

This code will execute whenever you make a selection from the Listbox.

 


10. The code for the marks button Click EventHandler is as following. Whenever you click on the Marks button of a any Listbox item this code will execute.

 



.

11. Now run the application. You will see the following List created in your application.

 


 

12. Now Select any Listbox item. Suppose we select the second item that is Fred. When you will Select it the values of Textblocks Studentnameblock and marksblock will change respectively.

 


 

13. When you click on Marks button given in front of the student name the corresponding student name and marks will be shown in the Textblocks given below the Listbox.

When you Click on the Marks button given in front of James the following output will be shown.

 


 

14. If hope this post will be helpful to you. Download the full project zip file from the link given below.

 

Download full project file Listboxselecteditem.zip

 

How to bind ListBox to data in Windows phone application – Introduction

As an application developer, you can create ListBox controls without specifying the contents of each ListBoxItem separately. You can use data binding to bind data to the individual items.

In this post, I will explain with the help of an example how to create a ListBox that populates the ListBoxItem elements by data binding to a data source.

Suppose you want to display a list of students with their marks in a windows phone app. If we specify the contents of each item separately it would take a lot of time. So we make a use of data binding. The steps that need to be followed are

1. Create a new project ListboxBinding.

2. Then open the MainPage.xaml and remove the XAML code for the StackPannel named TitlePanel and replace it with the following code so as to change the page name and application name .

3. Now add the following Xaml code in the Grid named ContentPanel so as to create a list box in the page having the name mylistbox and bind the target Textblocks nameblock and marksblock with data source name and marks respectively.

 


 

4. Now open the page MainPage.xaml.cs.

5. Create a public class called Resultclass having the two properties name and marks.

6. Then add the following code consisting of two global arrays for sample data to be used inside listbox named mylistbox.

 

7. Then we can add the following data into the listbox in two ways.

First method:

First method is to create a Separate list for the Listbox and adding the items into that list. After that set the itemsource property of the Listbox to that of list created.

We can do this with the help of following code.

Second method: In second method instead of making a separate listbox we can directly add the items into the listbox. We can do this with the help of following code.
If you face any problems while understanding the above code you can refer to the following blog post to understand the basics of data binding.

http://www.windowsapptutorials.com/windows-phone/data-binding-in-windows-phone-app-one-way-binding/

8. Now call any one of the following method in the Constructor of the MainPage .Both will give the same list as the Output when you will run the application.

Suppose I call the firstmethod. Then the Constructor of the MainPage will look like


9. Now run the application on Emulator. You will see the following list created on the MainPage .


10. If you want to know more about the Listbox selected item you can refer to the following blog post

How to work with ListBox selected item in Windows phone application

11. I hope this post will be helpful to you. Download the project zip file from the link given below.

Download Full Project file ListboxBinding.zip

Checkout a related post on using ListView in android.

Using ListView in Android

Data binding in Windows Phone app – One way binding

Data binding provides a simple way for Windows Phone apps to display and interact with data. In simple terms it provides a link between the target and source. For example if we consider a Textblock and a data source whose object needs to update the value of text in Textblock we can use data binding.

 

We will now explain One way data binding in which bindings update the target with the source data when the binding is created.

Here source is a object of the class which needs to update the text property of Textblock (target).

 

The steps that need to be followed are

 

1. First of all create a blank project and name it Databinding .

 


 

2. Replace the Xaml code of the Stackpanel named Titlepanel with the following code given below.

 


 

Code:

<StackPanel x:Name=”TitlePanel” Grid.Row=”0″ Margin=”12,17,0,28″>

<TextBlock Text=”Databinding” Style=”{StaticResource PhoneTextNormalStyle}” Margin=”12,0″/>

<TextBlock Text=”One way” Margin=”9,-7,0,0″ Style=”{StaticResource PhoneTextTitle1Style}”/>

</StackPanel>

 

3. Add a Textblock named myblock to the given page . And bind the text property of the Textblock with mytext which is the property of the Sample class which will be explained further.

 



 

Add the code given below to the Grid named ContentPanel given on the page

Code:

<TextBlock x:Name=”myblock” HorizontalAlignment=”Left” Margin=”63,80,0,0″ TextWrapping=”Wrap” Text=”{Binding mytext}” VerticalAlignment=”Top” Height=”57″ Width=”330″ FontSize=”28″/>

 

4. Open the Page MainPage.xaml.cs and Create a Public class having the name Sampleclass with a single property mytext.

 


 

Code:

public class Sampleclass

{

public string mytext { get; set; }

}

 

5. Add the function given below to the MainPage.xaml.cs .

 

Code:

public void initialize()

{

Sampleclass obj = new
Sampleclass();

obj.mytext = “One way data binding”;

myblock.DataContext = obj;

}

 

In the first line of the function we are creating a object of Sampleclass called obj. In the second line we are setting the mytext property of the object to “One way data binding”.

In the third line we set the source of the myblock by setting up its Datacontext property to obj.

 

6. We then call this function in the constructor of the MainPage.

 


 

7. Now when we run the application we will see that the Content of myblock will be “One way data binding” as shown below.

 


 

8. I hope this post will be helpful to you.Download the project zip file from the link given below.

 

Download full project