简体   繁体   English

从ListBoxItem获取选定的值,返回null

[英]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 我正在填充的LisBox出现问题,当我点击一个项目时,它给我错误

"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. 当我在获取所选值的行上放置一个断点时,它说它的值为null时,我已经在xaml中以静态方式声明了列表项,但没有任何问题。

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. 可能是由于在char数组中有几个相同的值而发生的。 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. SelectedValue属性不返回ListBoxItem对象,而是返回一个字符串。 See http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.controls.primitives.selector.selectedvalue.aspx for more information. 有关更多信息,请参见http://msdn.microsoft.com/zh-cn/library/windows/apps/windows.ui.xaml.controls.primitives.selector.selectedvalue.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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