WPF Bind JSON Array Using Listbox And DataTemplate In C#

Introduction

 
Windows Presentation Foundation (WPF) is Microsoft’s User Interface Framework that uses XAML to create desktop applications. As the name suggests it is meant to present users' data in the most comprehensive way using various capabilities provided by its GUI controls, resources, documents, layouts, and security. XAML on the other hand is Extensible-Mark-Up-Language which provides a declarative model to build the application's UI which is separate from the code-behind file. If you have used ASP.NET you will be more familiar with the file structure used in WPF. WPF comprises a .xaml file for XAML code and a back-end or code-behind file which can use C#, VB.NET (.xaml.cs/.xaml.vb files), or any other .NET language to provide the behavior of the desktop application.
 
This article is meant to showcase one of WPF's presentation capabilities using Student.json and a WPF data template.
 
So I'm assuming that you have created your WPF App (.NET Framework) project and named it as you like; in this case, I have named mine Students.
 
WPF Bind JSON Array using Listbox and DataTemplate in C# 
 
Here is my Students.json file which we intend to use and I have saved mine in my project folder /bin/Debug/Students.json.
  1. [  
  2.   {  
  3.     "ID""1",  
  4.     "Name""John Doe",  
  5.     "Gender""Male",  
  6.     "Class""32",  
  7.     "Seat""15",  
  8.     "Comment""An average student"  
  9.   },  
  10.   {  
  11.     "ID""2",  
  12.     "Name""Jane Doe",  
  13.     "Gender""Female",  
  14.     "Class""11",  
  15.     "Seat""14",  
  16.     "Comment""A highly exceptional student"  
  17.   },  
  18.   {  
  19.     "ID""3",  
  20.     "Name""Mary Williams",  
  21.     "Gender""Female",  
  22.     "Class""12",  
  23.     "Seat""14",  
  24.     "Comment""An average student"  
  25.   },  
  26.   {  
  27.     "ID""4",  
  28.     "Name""Peter Hughs",  
  29.     "Gender""Male",  
  30.     "Class""21",  
  31.     "Seat""14",  
  32.     "Comment""Below average student"  
  33.   },  
  34.   {  
  35.     "ID""5",  
  36.     "Name""Sara Gomez",  
  37.     "Gender""0",  
  38.     "Class""22",  
  39.     "Seat""14",  
  40.     "Comment""Above average student"  
  41.   }  
  42.     
  43. ]  
We are going to use the sample data as shown in the preceding JSON file. In Visual Studio our project is currently empty as shown below,
 
WPF Bind JSON Array using Listbox and DataTemplate in C# 
 
And here is the WPF default file is shown in the Solution Explorer,
 
WPF Bind JSON Array using Listbox and DataTemplate in C# 
  1. We need to create a Student class first in our solution so to do this we ‘Add a folder’ to our solution and name it Models. And in the models folder we right-click to 'Add a class’ which we will name students.

    WPF Bind JSON Array using Listbox and DataTemplate in C#

    WPF Bind JSON Array using Listbox and DataTemplate in C#
  1. In our students.cs class we add the following properties which will be used to create a student object and they should match the students.json properties.

    WPF Bind JSON Array using Listbox and DataTemplate in C#

  2. We need to create a presentation platform to show the user the student data and we do this in the XAML file, in this case, the MainWindow.xaml. And we start by changing the title of our main window to Students and adding the WindowState property to ‘Maximized’ so that the window opens in full-screen mode,

    WPF Bind JSON Array using Listbox and DataTemplate in C#

  3. After this we need to add a Resource to the Window that determines how our data template is going to look like as shown below,
    1. <Window.Resources>  
    2.       <!-- Data Template (applied to each bound task item in the task collection) -->  
    3.       <DataTemplate x:Key="students">  
    4.           <Border Name="border" BorderBrush="DarkSlateBlue" BorderThickness="2"  
    5.       CornerRadius="2" Padding="5" Margin="5">  
    6.               <Grid>  
    7.                   <Grid.RowDefinitions>  
    8.                       <RowDefinition Height="*"/>  
    9.                       <RowDefinition/>  
    10.                       <RowDefinition/>  
    11.                       <RowDefinition/>  
    12.                       <RowDefinition/>  
    13.                       <RowDefinition/>  
    14.                   </Grid.RowDefinitions>  
    15.                     
    16.                   <Grid.ColumnDefinitions>  
    17.                       <ColumnDefinition Width="Auto" />  
    18.                       <ColumnDefinition />  
    19.                   </Grid.ColumnDefinitions>  
    20.                     
    21.                   <TextBlock Grid.Row="0" Grid.Column="0" Padding="0,0,5,0" Text="ID:"/>  
    22.                   <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=ID}"/>  
    23.                   <TextBlock Grid.Row="1" Grid.Column="0" Padding="0,0,5,0" Text="Name:"/>  
    24.                   <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=Name}"/>  
    25.                   <TextBlock Grid.Row="2" Grid.Column="0" Padding="0,0,5,0" Text="Gender:"/>  
    26.                   <TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding Path=Gender}"/>  
    27.                   <TextBlock Grid.Row="3" Grid.Column="0" Padding="0,0,5,0" Text="Class:"/>  
    28.                   <TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding Path=Class}"/>  
    29.                   <TextBlock Grid.Row="4" Grid.Column="0" Padding="0,0,5,0" Text="Seat:"/>  
    30.                   <TextBlock Grid.Row="4" Grid.Column="1" Text="{Binding Path=Seat}"/>  
    31.                   <TextBlock Grid.Row="5" Grid.Column="0" Padding="0,0,5,0" Text="Comment:"/>  
    32.                   <TextBlock Grid.Row="5" Grid.Column="1" Text="{Binding Path=Comment}"/>  
    33.               </Grid>  
    34.           </Border>  
    35.       </DataTemplate>  
    36.   </Window.Resources>  
    This code should appear just below the title field and take note of the <Window.Resources></Window.Resources> tag. Resources are used in WPF to create a uniform look and feel in controls and windows and can be applied at different levels including application-level but we will not cover that in this article.
  1. After adding the resource to style our list we now need to create our UI and in this case, we are going to use WPF's DockPanel layout to present our data.

    WPF Bind JSON Array using Listbox and DataTemplate in C#

    Notice how the ItemTemplate locates the StaticResource name which in this case is ‘students’.

    Our design now should be looking like this,

    WPF Bind JSON Array using Listbox and DataTemplate in C#
  1. At this point we now need to go on our MainWindow.xaml.cs file which is the code-behind file to deserialize our Students.json file and present it in our WPF Listbox. To do this we need to add a Nuget Newtonsoft.Json package to our project. Right-click on your project solution in Solution Explorer and select 'Manage Nuget Packages’. Browse for Newtonsoft.Json package and click to install.

    WPF Bind JSON Array using Listbox and DataTemplate in C#

  2. Now we can open our MainWindow.xaml.cs file and on top of the page let us add the assemblies Newtonsoft.Json and Students.Models because we will need to use a class present in the Models folder namely the ‘student class as we will see later in the article,
    1. using Newtonsoft.Json;  
    2. using Students.Models;  
  1. Now add the following code to your MainWindow.xaml file.
    1. public partial class MainWindow : Window  
    2.     {  
    3.         public MainWindow()  
    4.         {  
    5.             InitializeComponent();  
    6.             OutputJson();  
    7.         }  
    8.   
    9.         public void OutputJson()  
    10.   
    11.         {  
    12.             try   
    13.             {  
    14.   
    15.                 string json = System.IO.File.ReadAllText(@"Students.json");  
    16.                 
    17.   
    18.                 lststudents.ItemsSource = JsonConvert.DeserializeObject<List<Student>>(json);  
    19.             }  
    20.             catch (Exception ex)  
    21.             {  
    22.                 MessageBox.Show(ex.Message);  
    23.             }  
    24.          }  
    25.     }  
  1. Save your project and press F5 or the 'Start' button at the top menu of the Visual Studio page. Your Output should look as follows,

    WPF Bind JSON Array using Listbox and DataTemplate in C#

Conclusion

 
This article shows how useful WPF can be when it comes to presenting data to users using various controls and methods to give users a quality experience.


Similar Articles