Search code examples
windows-phone-7listboxselectedindex

ListBox SelectedIndex is always -1


I have a Listbox with Button and Textblock as ItemTemplate. Button has an onClick event.

All i want is to get the index of the clicked item, but SelectedIndex property in my ListBox is always -1!

How can I get the index of the clicked item?


Solution

  • The problem is that the Button control is swallowing the mouse events to provide the Click behavior, so the ListBox never receives any events to tell it that the selection has changed.

    As @Alexander suggests, you could use an MVVM-style approach with commands to handle the action in a view model and pass the data context as the parameter.

    Alternatively, you could replace the Button with any other layout control and either use the gesture service from the Silverlight Toolkit or use the regular MouseLeftButtonUp event. In either instance, the mouse events will bubble up and enable the ListBox to handle selection.