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!!!
Comments
Anonymous
July 30, 2011
The item "lstData" appears only when you assign the ItemsSource to it. I think you might have to actually type this out in Visual Studio for yourself to get it to work. Also, how about dynamic updating once the values change. What do we do to update the listBoxEmployee?Anonymous
November 01, 2011
great! i'm looking for this! easy, clean and...it works! thanks!Anonymous
September 29, 2012
Thank you so much!Anonymous
November 25, 2012
Daniel, Daniel, I'm also trying to search solution for dynamic uploading - I try to use INotifyPropertyChanged. Maybe that will help you.Anonymous
May 01, 2013
ok. this may be simple for understanding but all fine when page load. try to refresh the list with data binding later point without page load and you have music. :)Anonymous
May 08, 2013
Thanks for this, but its not working.Anonymous
August 05, 2013
Hi, I was hoping you could help me, What if i want to bind to more than 1000 items, how will i handle that?Anonymous
August 06, 2013
For large list you should consider msdn.microsoft.com/.../microsoft.phone.controls.longlistselector(v=vs.105).aspxAnonymous
September 21, 2013
Great article.Anonymous
July 29, 2014
Thanks nice example