2012-03-12 59 views
0

我有我的ListPicker控件的問題。我已經實現了我的listpicker在我的頁面如下但是我在運行時收到IndexOutOfRangeException,我不太清楚如何來解決這個問題:ListPicker IndexOutOfRangeException

SettingsPage.xaml

<phone:PhoneApplicationPage.Resources> 
    <DataTemplate x:Name="SearchProviderItemTemplate"> 
     <TextBlock Text="{Binding SearchProvider}" /> 
    </DataTemplate> 
</phone:PhoneApplicationPage.Resources> 

<ScrollViewer x:Name="ContentPanel_Browser" Margin="12,0,12,0"> 
       <Grid> 
        <Grid.ColumnDefinitions> 
         <ColumnDefinition/> 
         <ColumnDefinition/> 
        </Grid.ColumnDefinitions> 
        <Grid.RowDefinitions> 
         <RowDefinition Height="Auto"/> 
         <RowDefinition Height="70"/> 
         <RowDefinition Height="70"/> 
         <RowDefinition/> 
         <RowDefinition/> 
         <RowDefinition/> 
        </Grid.RowDefinitions> 

        ... 

        <!-- Search Provider --> 
        <TextBlock Text="Search provider" Margin="12,7,12,8" 
         Grid.Row="3" VerticalAlignment="Bottom" 
         Foreground="{StaticResource PhoneSubtleBrush}"/> 
        <toolkit:ListPicker x:Name="SearchProviderListPicker" Grid.Row="4" Grid.ColumnSpan="2" Margin="12,0,12,0" 
             ItemTemplate="{Binding SearchProviderItemTemplate}" 
             SelectionChanged="SearchProviderListPicker_SelectionChanged" /> 
       </Grid> 
      </ScrollViewer>     

SettingsPage.xaml。 CS

string searchProvider; 

    String[] SearchProvider = 
    { 
     "Google", 
     "Bing", 
     "Yahoo", 
     "Ask", 
     "AOL" 
    }; 

    private void SearchProviderListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     string selectedItem = e.AddedItems[0] as string; //IndexOutOfRangeException was unhandled 

     switch (selectedItem) 
     { 
      case "Google": 
       searchProvider = "http://www.google.com/search?q="; 
       break; 
      case "Bing": 
       searchProvider = "http://www.bing.com/search?q="; 
       break; 
      case "Yahoo": 
       searchProvider = "http://search.yahoo.com/search?p="; 
       break; 
      case "Ask": 
       searchProvider = "http://www.ask.com/web?q="; 
       break; 
      case "AOL": 
       searchProvider = "http://search.aol.com/search?q="; 
       break; 
      //default: 
      // SearchProvider = "http://search.aol.com/search?q="; 
      // break; 
     } 

的IndexOutOfRangeException與線路中發生 '字符串將selectedItem = e.AddedItems [0]作爲串;'在SettingsPage.xaml.cs中。我記得看到如何解決這個StackOverflow的某個地方,但我現在找不到這個源。有關如何設置邊界或檢查以確保不會發生此異常的任何想法?提前致謝(任何代碼的幫助將幫助我對此是新的!)。

回答

2

由於AddedItems是一個IList,你能不能在你嘗試訪問它之前檢查它是否有一些項目?

喜歡的東西在方法的頂部以下應該解決的問題:

if (e.AddedItems.Count <= 0) 
{ 
    return; 
}