Reputation: 584
I have a long list selector
<phone:LongListSelector x:Name="BTDevices" SelectionChanged="BTDevices_SelectionChanged_1">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" FontSize="30" />
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
The function is defined as:
private void BTDevices_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
//here i want to get the index of the selected item
}
I tried the following line
int a = App.ViewModel.Items.IndexOf(sender as ItemViewModel);
But it always returns -1.
Upvotes: 1
Views: 4904
Reputation: 2916
When the SelectionChanged
event occurs, the sender
parameter of the event handler represents the object that triggered this event. It is of type Object
, but you can cast it to match your specific control type.
In this case, the LongListSelector
:
var myItem = ((LongListSelector) sender).SelectedItem as Model;
(Model represents the type of data your control handles).
Afterwards, look for that item in the ItemsSource
and retrieve its value :
var myIndex = ((LongListSelector) sender).ItemsSource.IndexOf(myItem);
You have named your control, so instead of (sender as LongListSelector)
, you could use its name, BTDevices
, but the code lines I wrote was intended to show you what's what with the sender
object.
Alternatively (and this is a more elegant way), shown by bland, you could use the EventArgs
for selection : e.AddedItems[0]
Upvotes: 4
Reputation: 1994
sender
is going to be who sent the fact that this event occurred. See SelectionChangedEventArgs at MSDN to know that you'll want to do e.AddedItems[0]
if single-select list, or if multi-select list, you'll need to loop over it:
foreach(var item in e.AddedItems)
Upvotes: 1