Search code examples
c#windows-phone-8longlistselector

How can I get LongListSelector SelectedItem as a string in WP8


I have a longlistselector like the below image. now I wanna get the text of the item user's tapped. I've searched a lot but no solution found ;( pay attention to the image please to give a sample code

http://amiryari.persiangig.com/image/stackoverflow-question.jpg


Solution

  • 1) Wire up the SelectionChanged event on the LongListSelector control:

    <phone:LongListSelector ItemsSource="{Binding MyListItems}"
                            SelectionChanged="LongListSelector_SelectionChanged">
    

    2) Retrieve the selected item from the AddedItems collection in the SelectionChangedEventArgs:

    private void LongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
         if (e.AddedItems.Count > 0)
         {
             var item = e.AddedItems[0];
         }
    }
    

    3) If your item is an object, and the text is displayed through a property, then you would have access to the text through the property on your object:

    MyListItemObject item = e.AddedItems[0] as MyListItemObject;
    MessageBox.Show(item.FullName);
    

    If your list is bound to a list of strings, then it would simply be the first item in the AddedItems collection:

    string fullName = e.AddedItems[0].ToString();
    MessageBox.Show(fullName);