3

I'm writing a Windows Phone 7 app with a ListBox. When an item in the ListBox is "clicked" or "hit" with a finger, what is the right event to trap that?

I have tried "SelectedIndexChanged" but that seems to fire on GoBack() when the app is TombStoned and an index of 0 is passed in (which seems odd).

I'm currently using MouseUp which seems to do the trick. But I'm not sure if that's correct.

Note: I discovered the reason SelectionChanged was firing when clicking back. When the Constructor for my Page was firing, and the ItemSouce for my ListBox was being set (databound) that would select the first item in the list and fire the SelectionChanved event. Since this was not initiated by user action, I solved this by simply creating an IsLoaded boolean and setting it to true after setting the ItemSource in the constructor and then checking for that in the event.

Francisco Alvarado
  • 2,815
  • 2
  • 26
  • 51
Omar Shahine
  • 1,935
  • 3
  • 22
  • 30
  • possible duplicate of [Is there a click behavior for a list?](http://stackoverflow.com/questions/4637793/is-there-a-click-behavior-for-a-list) – Mick N Jan 10 '11 at 06:04
  • Hi Omar, the above thread covers considerations concerning MouseUp, and repeat click/tap on same list items. – Mick N Jan 10 '11 at 06:06
  • ... also addressing the issue people usually have with SelectedIndexChanged (repeat presses won't fire) without resetting SelectedIndex first. – Mick N Jan 10 '11 at 08:00

1 Answers1

2

If you want to be notified when an item is selected you should catch the SelectionChanged event.

In the handler you check that e.AddedItems contains exactly one item:

void SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count == 1)
    {
        // .. do something
    }
}

On GoBack() you probably have items in the e.RemovedItems collection but nothing in e.AddedItems.

Francesco De Vittori
  • 9,100
  • 6
  • 33
  • 43
  • One quirk I found with this mechanism is that SelectionChanged fires when the ItemSource of a ListBox is updated (like in the Constructor). The SelectedIndex in that case is the first item in that list. – Omar Shahine Jan 14 '11 at 03:20
  • 2
    If, like me, you never really want the things to be selected and you just want them to be clickable, remember to set the SelectedIndex back to -1 once you're done, otherwise clicking the same thing twice won't do anything. – Chris Rae May 10 '11 at 19:34
  • HI Chris R, When we set the selectedIndex back to -1, it runs the SelectionChanged event again(as setting selectedIndex back to -1 is again another SelectionChange). So this event runs twice for each listbox item click. Therefore still wondering which is the best event to implement the listbox item click event. I tried with Tap event(Listbox) and would like to know the idea. Thank you very much... – JibW May 22 '12 at 13:34