简体   繁体   中英

Getting selected value from ListBoxItem, returns null

I'm having a problem with a LisBox that I am filling, when I tap on a item it gives me the error

"Value does not fall within the expected range."

and when I put a break point on the line that gets the selected value it says its value is null, I had the list items declared statically previously in xaml and it worked no problem.

Can any help me?

private void listbox_tapped(object sender, TappedRoutedEventArgs e)
    {
        ListBoxItem selected = (lbLetter.SelectedValue as ListBoxItem);

        int listitem = lbLetter.SelectedIndex;

        if (lbLetter.Items.Count != 0)
        {

            lbWord.Items.Add(selected);
        }

    }

   private void RandomizeListbox()
    {
        List<char> values = new List<char>();


        for (int i = 0; i<=MAXLETTERS; i++)
        {
            values.Add(RandomLetter());
        }
        lbLetter.ItemsSource = values;
    }

    public static char RandomLetter()
    {
        return alphabet[random.Next(alphabet.Length)];
    }

May be this happens because there several the same values in a char array. Try this:

for (int i = 0; i <= MAXLETTERS; i++)
{
    var c = RandomLetter();
    if(!values.Contains(c))
        values.Add(c);
}

Without testing it, I can assure you that the following line is incorrect:

ListBoxItem selected = (lbLetter.SelectedValue as ListBoxItem);

The SelectedValue property does not return a ListBoxItem object, it returns a string. See http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.selector.selectedvalue.aspx for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM