Windows Phone 7 - Binding Data to ListBox through Code

In Windows Phone 7 we need to display data programmatically. Below one demonstrates the simply way of binding data through code.

Suppose you have Emp class as below.

 public class Emp
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Let’s create List<Emp>

 List<Emp> myData = new List<Emp>()
{
    new Emp(){Id = 1, Name = "Wriju"},
    new Emp(){Id = 2, Name = "Writam"},
    new Emp(){Id = 3, Name = "Saswati"},
    new Emp(){Id = 4, Name = "Wrishika"},
    new Emp(){Id = 5, Name = "Baba"},
    new Emp(){Id = 6, Name = "Ma"}
};

After that format the ListBox to display it properly.

 <Grid>
    <ListBox Name="listBoxEmployee">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Id}"></TextBlock>
                    <TextBlock Text=" - "></TextBlock>
                    <TextBlock Text="{Binding Path=Name}"></TextBlock>
                </StackPanel>
            </DataTemplate>               
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

Now, you need to simply code to bind the data

 lstData.ItemsSource = myData;

This is a very simple example but useful in many scenario and applied to most of the data-bound application.

Namoskar!!!