Question

I'm a trying to get the value of the selected item in a LongListSelector. The contents of the lls are written from a xml file using a loop. But when I do use listFavs.SelectedItem.ToString();, it doesn't return the text in the selected item. What am I doing wrong?

C# code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.Xml;
using PhoneApp2.Resources;
using System.Xml.Linq;
using System.IO;
using System.IO.IsolatedStorage;
using System.Windows.Resources;

namespace PhoneApp2
{
    public class Favs
    {
        private string drank;

        public string Name
        {
            get { return drank; }
            set { drank = value; }
        }
        public Favs(string addition)
        {
            this.Name = addition;
        }
    }

    public partial class Favorites : PhoneApplicationPage
    {
        ObservableCollection<Favs> Favlist = new ObservableCollection<Favs>();

        public Favorites()
        {
            InitializeComponent();



            if (ThemeUsed.DarkTheme == 1)
            {
                ImageBrush SettingsLite = new ImageBrush();
                SettingsLite.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"resources/dark theme/feature.settings.png", UriKind.Relative));
                SettingsLite.Stretch = Stretch.Fill;
                btnSettings.Background = SettingsLite;
            }
            else
            {
                ImageBrush SettingsDark = new ImageBrush();
                SettingsDark.ImageSource = new System.Windows.Media.Imaging.BitmapImage(new Uri(@"resources/light theme/feature.settings.png", UriKind.Relative));
                SettingsDark.Stretch = Stretch.Fill;
                btnSettings.Background = SettingsDark;

            }
            //Menu (App bar)
            ApplicationBar = new ApplicationBar();

            ApplicationBar.Mode = ApplicationBarMode.Default;
            ApplicationBar.Opacity = 0.5;
            ApplicationBar.IsVisible = false;
            ApplicationBar.IsMenuEnabled = true;

            ApplicationBarIconButton btnAdd = new ApplicationBarIconButton();
            btnAdd.IconUri = new Uri("resources/dark theme/add.png", UriKind.Relative);
            btnAdd.Text = "Add to bar";
            ApplicationBar.Buttons.Add(btnAdd);
            btnAdd.Click += new EventHandler(btnAdd_Click);

            ApplicationBarIconButton btnSortaz = new ApplicationBarIconButton();
            btnSortaz.IconUri = new Uri("resources/dark theme/refresh.png", UriKind.Relative);
            btnSortaz.Text = "Sort A/Z Z/A";
            ApplicationBar.Buttons.Add(btnSortaz);
            btnSortaz.Click += new EventHandler(btnSortaz_Click);

            ApplicationBarIconButton btnSortdate = new ApplicationBarIconButton();
            btnSortdate.IconUri = new Uri("resources/dark theme/feature.calendar.png", UriKind.Relative);
            btnSortdate.Text = "Sort by date";
            ApplicationBar.Buttons.Add(btnSortdate);
            btnSortdate.Click += new EventHandler(btnSortdate_Click);

            //Populate LLL listBar
            listFavs.ItemsSource = Favlist;

            try
            {
                // copy the xml file to isolated storage
                using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    if (!file.FileExists("favorites.xml"))
                    {
                        StreamResourceInfo sr_en = Application.GetResourceStream(new Uri("Resources\\favorites.xml", UriKind.Relative));
                        using (BinaryReader br_en = new BinaryReader(sr_en.Stream))
                        {
                            byte[] data = br_en.ReadBytes((int)sr_en.Stream.Length);
                            //Write the file.
                            using (BinaryWriter bw = new BinaryWriter(file.CreateFile("favorites.xml")))
                            {
                                bw.Write(data);
                                bw.Close();
                            }
                        }
                    }
                    // work with file at isolatedstorage
                    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("favorites.xml", FileMode.Open, file))
                    {
                        XDocument xDoc = XDocument.Load(stream, LoadOptions.None);
                        var names = xDoc.Descendants("name").Select(n => n.Value).ToList();
                        foreach (string name in names)
                        {
                            Favlist.Add(new Favs(name));
                        }

                    }
                }
            }
            catch (Exception myExc)
            {
                Console.WriteLine(myExc.Message);
            }
        }

        private void btnSettings_Click(object sender, RoutedEventArgs e)
        {
            //Open/Close menu(app bar)
            if (ApplicationBar.IsVisible == false)
            {
                ApplicationBar.IsVisible = true;
            }
            else
            {
                ApplicationBar.IsVisible = false;
            }

        }
        private void btnSortaz_Click(object sender, EventArgs e)
        {
            //sort AZ ZA function here
            ApplicationBar.IsVisible = false;
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            //Add cocktail to bar function here
            ApplicationBar.IsVisible = false;

        }
        private void btnSortdate_Click(object sender, EventArgs e)
        {
            //Sort by date function here
            ApplicationBar.IsVisible = false;

        }

        private void listFavs_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string text = listFavs.SelectedItem.ToString();
            MessageBox.Show(text);
        }
    }
}

XAML code:

<phone:PhoneApplicationPage
    x:Class="PhoneApp2.Favorites"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot">
        <Grid.Background>
            <ImageBrush Stretch="Fill" ImageSource="/Assets/AlignmentGrid.png"/>
        </Grid.Background>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->

        <!--ContentPanel - place additional content here-->

        <!--ContentPanel - place additional content here-->

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="Header" Grid.Row="0" Margin="12,17,0,616" Grid.RowSpan="2">
            <TextBlock Text="Cocktail" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0,242,46"/>
            <TextBlock Text="Favorites" Style="{StaticResource PhoneTextTitle1Style}" Margin="10,50,101,0" FontWeight="Bold"/>
            <Button x:Name="btnSettings" Content="" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="367,60,0,-50" Height="86" Width="91" Click="btnSettings_Click">
                <Button.Foreground>
                    <ImageBrush Stretch="Fill"/>
                </Button.Foreground>
                <!--<Button.Background>
                    <ImageBrush Stretch="Fill" ImageSource="feature.settings.png"/>
                </Button.Background>-->
            </Button>
        </Grid>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,157,12,0">
            <phone:LongListSelector x:Name="listFavs" HorizontalAlignment="Left" Height="601" VerticalAlignment="Top" Width="456" SelectionChanged="listFavs_SelectionChanged">
                <phone:LongListSelector.ItemTemplate>
                    <DataTemplate>
                        <Button Content="{Binding Name}" FontSize="36" HorizontalContentAlignment="left"  HorizontalAlignment="Left" Height="82" Margin="0,-11,0,0" VerticalAlignment="Top" Width="456" Padding="0,0,0,0" BorderThickness="0">
                        </Button>
                    </DataTemplate>
                </phone:LongListSelector.ItemTemplate>
            </phone:LongListSelector>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>
Was it helpful?

Solution

try this code to get 'name' text:

string name = (listFavs.SelectedItem as Favs).Name;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top