Search code examples
vb.netxamlwindows-phone-8longlistselector

Get the selected index in a LongListSelector


I'm using a LongListSelector for a WP8 app. I searched on several websites but did not found if there was a way to know the index of the item the user taped in the List. If anyone has an idea, it would be nice. Thanks

`

        <phone:LongListSelector x:Name="ListeNotes" Height="535" Width="426" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="36" Margin="54,0,0,0">

            <phone:LongListSelector.ItemTemplate>
                <DataTemplate>

                    <TextBlock Text="{Binding Titre}"/>

                </DataTemplate>

            </phone:LongListSelector.ItemTemplate>

        </phone:LongListSelector>

`


Solution

  • I'd create in code-beind or ViewModel (depending on what are you using), public variable

    Public Int32 itemSelectedIndex {get;set;} //This is a public variable, therefore add it inside your class
    

    and bind it to SelectedIndex as following:

    <phone:LongListSelector x:Name="ListeNotes" Height="535" Width="426" HorizontalAlignment="Left" VerticalAlignment="Top" FontSize="36" Margin="54,0,0,0" SelectedIndex ="{Binding itemSelectedIndex, UpdateSourceTrigger = PropertyChanged}">
    

    don't forget to add datacontext reference in code behind

    Public void MainWindow()
    {
    InitializeComponents();
    this.DataContext = this;//this makes sure that you can bind public varibles to XAML
    }
    

    Afterwards you simply reference itemSelectedIndex anywhere in your code and it will return selected value (e.g. System.Windows.MessageBox.Show(itemSelectedIndex.ToString());