I have a Listbox filled with Buttons. When the buttons is clicked then a new Page shows. But i wanna have the selected index of the listbox when i click on the button. But the listboxitem is never selected. Is there a way to get the index where the button lies by clicking the button. Thanks for help.
Example code
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Click="ViewDetail_Click" Content="{Binding Path=Area}"></Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The data context of the button will contain the source data item corresponding to the list item. You’ve not shown what your
ItemsSourceis for the list, so I can’t show exactly what code you’d need. But something like this:Of course, if the reason you’re asking for the index in the first place is because you want to get hold of the corresponding data item, you don’t actually need the index at all – the item’s already right there in the data context.
By the way, I wouldn’t use a
ListBoxhere. The main thingListBoxbrings to the party is selection, but by putting buttons in as the items, you’re defeating that – as you’ve already discovered, the button is handling the mouse input before the list box has a chance to, meaning that you can’t actually select the items. At which point, why have aListBox? A baseItemsControlprobably makes more sense. (Wrapped in aScrollViewerif you need scrolling.)