Reader Level:
ARTICLE

Select ListBox Item on the Hold Event in Windows Phone

Posted by Dhananjay Kumar Articles | Windows Phone February 26, 2012
In this article you will see how to use a ListBox in Windows Phone.
  • 0
  • 0
  • 9273

Introduction

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:

html5.jpg

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:

image2.jpg
Finally, I am setting an ItemsSource of the ListBox as below. lstPhotos is a list of Photos.
image3.jpg
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.

 image4.jpg

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.

Conclusion

So in this post you saw how to use a ListBox in Windows Phone. I hope this quick article is useful. Thanks for reading.

COMMENT USING

Trending up