In this article you will see how to use a ListBox in Windows Phone. The ListBox control is used to display a list of items to a user. In a ListBox we can select more than one item. ListBox provides two property arrays into which you can place data: List and ItemData.
I was working on an application and I had to select a List Box Item on the hold event. My List Box was as below:
You see in the List Box, I have put an Image control and binding Source and Tag dependency property of the image to the data source.
At the code behind, I got an entity class Photo as below:
Finally, I am setting an ItemsSource of the ListBox as below. lstPhotos is a list of Photos.
Now the question arises of how to set a particular image from a list of images in a ListBox on the hold event. When the user holds a particular image in a ListBox, that image should get selected. For that I have raised a hold event on the Image control in the List Box and in the hold event we need to fetch the selected image as the data context.
In the above code you can see that I am getting the data context of the selected image in the instance of the entity class photo. In this way you can select a ListBox item on the hold event.
Before I conclude, one point to keep in mind is that you need to raise the Hold event on the container inside the ListBox. For example, if you have a StackPanel inside a DataTemplate then you need to raise the Hold event on the StackPanel. In my case there is no container but an Image so I am raising the Hold event on the Image control. Avoid raising the hold event on the ListBox itself else you will get a NullReference exception.
So in this post you saw how to use a ListBox in Windows Phone. I hope this quick article is useful. Thanks for reading.