Binding Object List With ListBox in Windows Phone 8

Introduction

In this article we will learn how to bind a list of objects with a List Box in Windows Phone 8. It's a great way of adding and removing the items from the List Box at run time. In this method we just add an empty List Box to our application and populate it programmatically using data binding. So let's start.

Binding The List and List Box

In this article I'll focus only on the list of objects. We want to bind the list of objects with the List Box. Binding means connecting your collection of objects with the List Box so that they can be displayed in your app.

The following simple steps will help you in binding your List Box and list:

  1. Add a List Box to your application page.
  2. Provide it a name as itemList.
  3. Add an Item Template to your List Box.
  4. Inside the item template add the data template.
  5. Now inside the data template add the appropriate control to show your object fields.
  6. Create a list of objects in code behind.
  7. Set the item source of List Box equal to the Step 3 list.

the following code implements the preceding steps.

XAML

<phone:PhoneApplicationPage

    x:Class="Demo.MainPage"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"

    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"

    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    FontFamily="{StaticResource PhoneFontFamilyNormal}"

    FontSize="{StaticResource PhoneFontSizeNormal}"

    Foreground="{StaticResource PhoneForegroundBrush}"

    SupportedOrientations="Portrait" Orientation="Portrait"

    shell:SystemTray.IsVisible="True">

 

    <!--LayoutRoot is the root grid where all page content is placed-->

    <Grid x:Name="LayoutRoot" Background="Transparent">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="*"/>

        </Grid.RowDefinitions>

 

        <!--TitlePanel contains the name of the application and page title-->

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">

            <TextBlock Text="Demo" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>

            <TextBlock Text="Binding-Object" Margin="9,-7,0,0" FontSize="40"/>

        </StackPanel>

 

        <!--ContentPanel - place additional content here-->

        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">

            <Grid.RowDefinitions>

                <RowDefinition Height="243*"/>

                <RowDefinition Height="406*"/>

            </Grid.RowDefinitions>

            <Button Name="pushBtn" Content="Add" Click="addClick" HorizontalAlignment="Left" Margin="0,10,0,0" VerticalAlignment="Top" Width="225"/>

            <Button Name="popBtn" Content="Remove" Click="popClick" HorizontalAlignment="Left" Margin="225,10,0,0" VerticalAlignment="Top" Width="221"/>

            <ListBox Name="itemList" Margin="0,87,0,10" Grid.RowSpan="2">

                <ListBox.ItemTemplate>

                    <DataTemplate>

                        <StackPanel Orientation="Horizontal">

                            <TextBlock Text="{Binding Index}" FontSize="45" Margin="0,10" Width="204"></TextBlock>

                            <TextBlock Text="{Binding Value}" FontSize="35" Width="246" Margin="0,10"/>

                        </StackPanel>

                    </DataTemplate>

                </ListBox.ItemTemplate>

            </ListBox>

        </Grid>

    </Grid>

 

</phone:PhoneApplicationPage>

C# Code Behind
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Navigation;

using Microsoft.Phone.Controls;

using Microsoft.Phone.Shell;

using Demo.Resources;

using System.Threading;

using Nokia.Music.Types;

 

namespace Demo

{

    class test

    {

        private int _index;

 

        public int Index

        {

            get { return _index; }

            set { _index = value; }

        }

 

        private string _value;

 

        public string Value

        {

            get { return _value; }

            set { _value = value; }

        }

       

 

    }

 

    public partial class MainPage : PhoneApplicationPage

    {

        // Constructor

        public MainPage()

        {

            InitializeComponent();

            for (int i = 0; i < 5; i++)

            {

                list.Add(new test() {Index=i+1,Value="Item: "+(i+1) });

            }

            itemList.ItemsSource = list;

        }

        private static int i = 5;

        private List<test> list=new List<test>();

        private void popClick(object sender, RoutedEventArgs e)

        {

            if (i > 0)

            {

                list.RemoveAt(i - 1);

                itemList.ItemsSource = null;

                itemList.ItemsSource = list;

                i--;

            }

 

        }

 

        private void addClick(object sender, RoutedEventArgs e)

        {

            list.Add(new test() { Index = i + 1, Value = "Item: " + (i + 1) });

            itemList.ItemsSource = null;

            itemList.ItemsSource = list;

            i++;

        }

    }

}

In the code above I'm resetting the item source each time to reflect the changes. It's not a preferred way of doing this but it's good for beginners. The best way to reflect the changes is to use the INotify property Change or by adding individual items using the add method of list items. In the code above I'm binding the test class objects with the List Box "itemList". The Test class object has two properties so I have added two text blocks to the data template to display them. Inside the text block the text is bound to the index and value properties of an object. Here you need to specify the name of the getter and setter, not the property name.

 

 

  


Summary

That's all for this article. I hope you have found it useful. In case of any doubt feel free ask in the comments section.

Up Next
    Ebook Download
    View all
    Learn
    View all