"SelectedIndex must always be set to a valid value" WP8 中的列表选择器问题



我尝试了这个网站上给出的所有解决方案,但在我的情况下都失败了。即使这样也不能解决我的问题,请建议任何其他解决方案或解释为什么它不起作用。

我有一个产品列表选择器它被绑定在代码后面,比如

listpickerProducts.ItemSourde = <myProductList>

和以下代码是在OnNavigateTo方法中编写的,用于更改此列表选择器的selectedIndex,但会抛出异常,因为它总是设置selectedIndex = -1。

  listpickerProducts.ItemSourde = <myProductList>
  listpickerProducts.SelectionChanged += listpickerProducts_SelectionChanged;
  listpickerProducts.SelectedIndex = 1; //Here it throws exception : SelectedIndex must always be set to a valid value`
我的xaml代码如下:
 <toolkit:ListPicker x:Name="listpickerProducts">
                <toolkit:ListPicker.FullModeItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock x:Name="txtPID" Text="{Binding PID}" Visibility="Collapsed"/>
                            <TextBlock x:Name="txtProdName" Text="{Binding ProdName}" FontSize="30"/>
                            <TextBlock x:Name="txtUnit" Text="{Binding Unit}" Visibility="Collapsed"/>
                        </StackPanel>
                    </DataTemplate>
                </toolkit:ListPicker.FullModeItemTemplate>
                <toolkit:ListPicker.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock x:Name="txtPID" Text="{Binding PID}" Visibility="Collapsed"/>
                            <TextBlock x:Name="txtProdName" Text="{Binding ProdName}" />
                            <TextBlock x:Name="txtUnit" Text="{Binding Unit}" Visibility="Collapsed"/>
                        </StackPanel>
                    </DataTemplate>
                </toolkit:ListPicker.ItemTemplate>
            </toolkit:ListPicker>

listpickerProducts_SelectionChanged事件如下:

    private void listpickerProducts_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {          
       int index = listpickerProducts.SelectedIndex;
     //  MessageBox.Show(index.ToString());
       if (index >= 0) 
       { 
         lblUnit.Text = (listpickerProducts.SelectedItem as Products).Unit.ToString();
         lblRateValue.Text = (listpickerProducts.SelectedItem as Products).Rate.ToString();
       }
     }    

我认为异常消息本身是非常有用的。当您导航到该页面时,您正在设置所选索引。在这一点上,ListPicker可能甚至没有加载。即使加载了,它也还没有完成绑定。它没有任何项,索引1无效。您可以在这里尝试几种方法。

  1. 尝试在listpickerProducts.Loaded事件中设置索引。如果这有效,你就可以开始了。
  2. 注释掉设置索引的行。不要设置索引。现在,运行应用程序并确保您的ListPicker确实填充了项目。可能有一些绑定错误,ListPicker可能没有项,使得索引1无效。

试试这个:

它会帮助你:

private void listpickerProducts_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (listpickerProducts.SelectedIndex > -1)
    {
        int index = listpickerProducts.SelectedIndex;
        if (index >= 0)
        {
            lblUnit.Text = (listpickerProducts.SelectedItem as Products).Unit.ToString();
            lblRateValue.Text = (listpickerProducts.SelectedItem as Products).Rate.ToString();
        }
    }
}

另一件事是,ListPicker似乎需要在产品对象或项目源中使用的任何类中实现Equals。

最新更新