HisTech Up

Walkthrough: Data Binding for UWP – Part 1 – Classic Binding

Introduction

user

Christian Hissibini

I am a Tech enthusiast who loves to blend Dev & Design on Web and Mobile Platforms. I am also a Windows Platform Dev MVP


LATEST POSTS

Xamarin: Stratégie de partage de code pour iOS et OS X 10th April, 2016

Walkthrough: Data Binding for UWP – Part 3 – Compiled Binding 31st March, 2016

Windows Apps

Walkthrough: Data Binding for UWP – Part 1 – Classic Binding

Posted on .

Classic Data Binding

 Create a blank Universal Windows app

We will begin by creating a project from the Blank app template.

  1. In a new instance of Visual Studio 2015, choose File > New > Project to open the New Project dialog. Navigate to Installed > Templated > Visual C# > Windows > Universal and select the Blank App (Universal Windows)
  2. Name your project DataBindingHOL and select the file system location where you will save your Hands-on Lab solutions. We have created a folder in our C: directory called HOL that you will see referenced in screenshots throughout the labs.

Leave the options selected to Create new solution and Create directory for solution. You may deselect both Add to source control and Show telemetry in the Windows Dev Center if you don’t wish to version your work or use Application Insights. Click OK to create the project.

 

Create a new Blank App project in Visual Studio 2015

Figure 1 Create a new Blank App project in Visual Studio 2015

  1. Set your Solution Configuration to Debug and your Solution Platform to x86. Select Local Machine from the Debug Target dropdown menu.

Configure your app to run on the Local Machine. - Visual Studio 2015

Figure 2 Configure your app to run on the Local Machine.

  1. Build and run your app. You will see a blank app window with the frame rate counter enabled by default for debugging.

The blank universal app running in Desktop mode.

Figure 3  The blank universal app running in Desktop mode.

  1. Return to Visual Studio and stop debugging.

 

Create the Models

Think of the models as the business objects.  A Model should know about nothing about the user experience – specifically the View or how it is implemented using a ViewModel.  The Model only interact with system and data services.

  1. Next right mouse click on the solution and Add a New Folder called Models.
  2. Now right mouse click on the Models directory and add a new C# Class called cs.
  3. Defines the Alien object:

 

public class Alien 
    {
        public string Name { get; set; }

        public string Avatar { get; set; }

        public int Power { get; set; }
    }

 

Build the ViewModels

Now we get to the interesting part of the MVVM work – building the ViewModels.

The ViewModel is where you encapsulate any code or data that your UX or View will need.  It is important that ViewModel only knows about and encapsulates the Model – but it shouldn’t be responsible for any Business Logic or Business Constraints – that should all be in the model. And on the other side, the ViewModel should know nothing about the specifics of the Views and UX that use it.

For those of you less familiar with the MVVM approach, here is a quick summary a two important constructs:

  • INotificationPropertyChanged.  INotificationPropertyChanged (or INPC) is an interface that describes how an object can participate in XAML bindings. The Binding system knows this interface and it uses it observe when properties on your objects have changed.
  • ObservableCollection.  Normal Lists and other IEnumerables don’t support notifications of changes that the View will need. The ObservableCollection class does this so we create one of these within our MainPageViewModel to keep track of our Aliens collection.
  1. Let’s go. Create a new directory for ViewModels.
  2. And add a Class called MainPageViewModel.cs.
  3. Add the following code to MainPageViewModel.cs
using System;
using System.Collections.ObjectModel;
using DataBindingHOL.Models;
 
namespace DataBindingHOL.ViewModels
{
    public class MainPageViewModel
    {
        public MainPageViewModel()
        {
            Random random = new Random();
 
            for (int i = 0; i < 50; i++)
            {
                var alien = new Alien
                {
                    Name = string.Format("Alien {0}", i),
                    Avatar = string.Format("/Assets/{0}.png", i),
                    Power = random.Next(0, 1000)
            };
 
                Aliens.Add(alien);
            }
     
        }
        public ObservableCollection Aliens { get; private set; } = new ObservableCollection();
    }
 
   
}

As you can see we’ve created a ViewModel for our MainPage that is called MainPageViewModel.  Next we add an ObservableCollection<Alien> property called Aliens to provide a Xaml bindable implementation of our list of Aliens. We load 50 Alien to the collection in the constructor.

 

Create the Views

This is where you create the user experience – in Windows apps you do this declaratively with XAML markup language and design tools.  The View uses properties and actions on the ViewModel to get the job done.

Okay, we are mostly done with the coding part of our application.  Now we just need to create the View and we will do that using XAML.

Delete the default MainPage.xaml file.

  1. Create a new directory for Views.
  2. And add a New Blank Page called MainPage.Xaml
  3. Paste in the following in place of the existing Grid.

 

      1. In addition, add the following namespaces to the <Page> tag:
xmlns:vm="using:DataBindingHOL.ViewModels"
  1. And finally, set the data context.
 
       
        
    

What we got “vm”, the symbol here refers to the ViewModel namespace. And that we doing is to get an instance of MainPageViewModel

Our view is very simple – it consists of a Grid with two columns.  On the left is a GridView displaying a list of Alien by using classic binding.  And on the right, nothing for the moment.

we’re binding the item source using a binding statement to the “Aliens” property of our data context.

Every item in the list is going to be displayed using this XAML inside the data template, and you see we’ve got a TextBlock an Image control, and we’re simply binding the text property of the TextBlock to the Name property and the Image Source to the Avatar property of data item of an Alien object. So now, if you run the app we should see a simple GridView with 50 Aliens.

profile

Christian Hissibini

I am a Tech enthusiast who loves to blend Dev & Design on Web and Mobile Platforms. I am also a Windows Platform Dev MVP

There are no comments.

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

View Comments (0) ...
Navigation