Data Binding In Universal Windows Platform

In this article you will learn about data binding in UWP and contains necessary step to bind data with your UI.

Data binding is a way for your app’s UI to display data, and optionally to stay in sync with that data. Data binding allow you to separate the concern of data from the concern of UI. And that results in a simpler conceptual model as well as better readability, testability, and maintainability of your app. In markup, you can choose to use either the {x:Bind} markup extension or the {Binding} markup extension. And you can even use a mixture of the two in the same app—even on the same UI element. {x:Bind} is new for Windows 10 and it has better performance. {Binding} has more features.

Create a new UWP Project

Add a new class (model) in your project. I am going to use Movies Example.

newmodel.PNG

Right click on project and create a new folder. Rename it as Model (this folder is created to follow separation of concerns).

Right click on model and create new item select class and name it Movies.

class

new item

Make sure you make the class public and define attribute you want to include.

  1. public class Movies  
  2. {  
  3.    public string Name { getset; }  
  4.    public string Genre { getset; }  
  5.    public string Year { getset; }  
  6.    public string CoverImage { getset; }   
  7.     

Now go to your Main page.xaml and make UI for this class. In each control data is bind with the class attribute.

  1. <GridView Name=”_gridview” >  
  2.         <GridView.ItemTemplate >  
  3.             <DataTemplate >  
  4.   
  5.    
  6.   
  7.                //your contorls here  
  8.   
  9.             </DataTemplate>  
  10.         </GridView.ItemTemplate>  
  11. </GridView>

You can use ListView instead of GridView to display your data in list form for mobile Interface. The final result should look like the following,

xamlview.PNG

Ignore StackPanel if you don't have idea about this. Image and textblocks are using the property of their content and using Binding statement with the attribute of class Movies.

Your UI is ready and now its time to fill it with some data. Go to MainPage.xaml.cs file and create Movies object. Put them in list or observable collection and bind the item source property of GridView with that list.

csfile.PNG

Now run the application it will show data in grids just like the following,

finalproduct.PNG

Source code.