[Basic for Absolute Beginner] - [Part 2] - Layout with XAML

This is part 2 of the Layout with XAML – Basic for Absolute Beginner series

Part 1 is here: [Windows Phone – Silverlight] Layout with XAML – Basic for AbsoluteBeginner - Part 1

As you already know, besides the Stackpanel and the Grid, XAML has another basic control: the ListBox (and GridView, ListView, if you are writing for Windows 8 or WPF apps)

Within the scope of this post, I will cover the ListBox and how to design it in the UI.

In the same series:

[Basic for Absolute Beginner] – [Part 1] – Layout with XAML 1

[Basic for Absolute Beginner] – [Part 2] – Layout with XAML 2

[Basic for Absolute Beginner] – [Part 3] – App’s Structure and how to customize it

[Basic for Absolute Beginner] – [Part 4] – Basic Steps for a new app

[Basic for Absolute Beginner] – [Part 5] – Analytics for your apps

[Basic for Absolute Beginner] - [Part 6] - Source Control

Table of contents

1. LISTBOX CONTROL

The ListBox control is used to display a list of items.

That list has a certain look and a certain data type, whichever you pick

For example: “Top 30 most watched videos on youtube” is the kind of data we would use a ListBox to display

1.1. The important properties

1.1.1. ItemsSource

ItemsSource is the data source. Where does this Listbox get its data from?

ItemsSource can be a List or an ObservableCollection; we’ll talk about it later on

1.1.2. SelectedIndex

The name says it all. This is the item currently selected in your listbox. During construction this value is -1

Note that items start at 0. If you have 5 items, they are numbered from 0 to 4

1.1.3. SelectedItem

This is yet another property. Its value is null at construction. And when the user picks some item in the listbox, that item is reflected into this property.

This property’s data type is Object, so when using it you have to cast it to the list’s data type

1.1.4. DataConext – the data context

DataContext is used in some advanced binding cases; for now you don’t need to worry about it

1.2. Trying it out

Create a Windows Phone project

In the LayoutRootGrid, create a Listbox

Pick the Property tab while this listbox is selected

In the Items section, add a few new items to the listbox

Then pick Listbox Item and hit the Add button

As you can see, an item with index = shows up along with its properties

Then add the content as in the picture below:

Hit run and you will see how the listbox behaves

http://youtu.be/8cu_REIkxPQ

Now you know the most basic way the Listbox works. Let’s “dig deeper” into the XAML world

2. DataBinding – a wonderful way to display data

The Listbox is used most of all with this DataBinding technique

This technique lets you display data from some source onto the listbox. That source can be a List, or an Observable Collection

Many people, when they think of DataBinding, immediately think of the MVVM pattern.

Hold on — as someone just starting out, you probably don’t know what MVVM is or what it looks like.

So let’s look at a few basic concepts and techniques first

2.1. Preparation

To follow along with this post, you need these tools:

Visual Studio — you surely have this one already

ReSharper: helps you automate the boring but necessary work. Note that this is commercial software

Once ReSharper is installed, let’s continue

2.2. The data type

To bind data onto a ListBox we need a “data source”, and that data source has to be built from some data type, since it is a list of items

For example: a list of strings, a list of integers

But you can also create your own data type, like a “list of dishes” type

So how do we create a data type?

Create a new Folder and name it Model

Create a new class file in that folder named DataStructure

A new DataStructure class is created. You can delete it and start defining your own class

As in the picture above, you have 3 private fields. Hold on — private members can’t be accessed outside the class, so we need to create public properties for them

Before creating the public properties, we should do something else first: implement the INotifyPropertyChanged Interface

This Interface makes binding data to the UI “continuous”. That is, when the data in the data source changes, that change is immediately shown on the UI.

Say you have 5 FoodItems with 5 different names. You want to change the name of the 2nd item: you just reach item 2 and change the value of the foodName property, and the UI updates automatically without a single extra line of code

Okay, let’s declare the properties

After implementing the Interface, you are required to declare 1 event and one Method in your class

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChangedEventHandler handler = PropertyChanged;

    if (handler != null)
    {
      handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

If you have ReSharper, everything is much simpler

Then pick Yes

And you will see the result

Note that ReSharper adds a file to the Properties of the Project you are writing

A Dropbox file for those of you without ReSharper: https://db.tt/ycsvjt1S

Right, now let’s create the Public Properties

Once again, ReSharper helps us out.

Put the cursor below the Private fields, pick ReSharper > Edit > Generate Code…

Pick Property in the dialog that shows up

Check all 3 fields, and check the “Notify on Property Changes” option too

And you end up with 3 properly written properties like this

2.3. The data source

You have a data type, now you need a data source

Create a new Folder named Data

Create a new class named StaticData in that Folder

Declare a static ObservableCollection variable

With ReSharper it automatically adds the Namespaces you need. Here the FoodItem class belongs to the TestAd.Model namespace

The result looks like this:

2.4. Loading the data

Now let’s load data into this ObservableCollection

Open the code behind file of the page that holds the listbox you created in part 1

Write it as follows — this style should look familiar from the post: [Windows Phone] Where to put LoadData method

Step 1: check whether the data already exists

The basic characteristic of declaring LoadData this way is that when we navigate to this page, or when the elements on the UI change, the OnLoaded event gets called again.

So we adjust the OnLoaded event to prevent reloading the data, like this:

private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{ 
  if (StaticData.FoodItemCollection.Count == 0)
  {
    LoadData();
  }
}

Add the following code to the LoadData function

private void LoadData() 
{ 
  for (int i =0;i <5;i++)
  { 
    FoodItem foodItem =new FoodItem();
    foodItem.Id = i;
    foodItem.FoodName ="Food Name is " +i;
    foodItem.ImageLink ="FoodItem_" + i + "_imageLink";
    StaticData.FoodItemCollection.Add(foodItem);
  }
}

The goal of the code above is to add 5 fake items to the FoodItemCollection.

2.5. Binding

So we have the data, the data source and the listbox — now let’s bind this data to the listbox

This is done with a single line of code.

Give your listbox a name:

Change the OnLoaded event to this:

private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
  if (StaticData.FoodItemCollection.Count == 0)
  { 
    LoadData();
    FoodListBox.ItemsSource = StaticData.FoodItemCollection;
  }
}

Then run it on the Emulator or on a Device, whichever you prefer

And this is your result

2.6. DataTemplate

So the data is now shown on the UI, but not the way you want it

That’s why we create a DataTemplate for the Listbox — to “define” how the data is displayed

Go into your XAML code and click Document Outline

Document Outline is where everything on your UI is shown as a tree

Right click on your ListBox and pick

Name your DataTemplate and hit OK

If you pick Define in Application, this DataTemplate can be used on every page in your project without declaring it again

While designing, you can see your design rendered visually

Hit run one more time and everything is exactly the way you want it

3. Event Handling

So you have a listbox — now let’s wire up some events on it to tell the user which Listbox item they picked

In FoodListBox’s Property panel, click the Event button

Double Click the “Selection Changed” event to declare the event

Add the following code into the newly created event

if (FoodListBox.SelectedIndex != –1)
{
  FoodItem foodItem = FoodListBox.SelectedItem as FoodItem;
  MessageBox.Show(foodItem.FoodName);
}

Run it and pick any item

Pretty great, isn’t it

That’s all — see you in the next episode of the Absolute Beginner Series