Share via


UWP Data Binding

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.

Steps

Create a new UWP Project

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

https://ayyazahmadtarar.files.wordpress.com/2015/11/newmodel.png?w=736

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.

https://ayyazahmadtarar.files.wordpress.com/2015/11/class.png?w=736

https://ayyazahmadtarar.files.wordpress.com/2015/11/new-item.png?w=736

Class & attributes

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

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

XAML

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 controls here  
  8.   
  9.             </DataTemplate>  
  10.         </GridView.ItemTemplate>  
  11. </GridView> 

ListView

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,

https://ayyazahmadtarar.files.wordpress.com/2015/11/xamlview2.png?w=736

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.

Add 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.

https://ayyazahmadtarar.files.wordpress.com/2015/11/csfile.png?w=716&h=323

Run application

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

https://ayyazahmadtarar.files.wordpress.com/2015/11/finalproduct.png?w=736

Download source code

Github code.