2012-09-13 2 views
1

ObservableCollection에 개체를 추가하려고합니다. 이 사이트의 몇 가지 질문에서 언급했듯이, 항목을 추가하기 전에 컬렉션을 인스턴스화하려고했습니다. 그러나 여전히 오류가 발생합니다. 여기ObservableCollection에 항목을 추가하는 중 NullReferenceException이 발생했습니다.

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
    { 
     // Define the query to gather all of the idea items. 
     var wordItemsInDB = from WordItem word in wordsDB.WordItems 
          select word; 

     // Execute the query and place the results into a collection. 
     WordItems = new ObservableCollection<WordItem>(wordItemsInDB); 

     // Call the base method. 
     base.OnNavigatedTo(e); 
    } 

onNavigatedTo 재정의 한

//Datacontext for local database 
private WordDataContext wordsDB; 

//Observable collection for binding 
private ObservableCollection<WordItem> _wordItems = new ObservableCollection<WordItem>(); 
public ObservableCollection<WordItem> WordItems 
{ 
    get 
    { 
     return _wordItems; 
    } 
    set 
    { 
     if (_wordItems != value) 
     { 
      _wordItems = value; 
      NotifyPropertyChanged("WordItems"); 
     } 
    } 
} 

새 항목을

private void newIdeaAddButton_Click(object sender, RoutedEventArgs e) 
    { 
     //// Create a new idea item based on the text box. 
     //WordItem newIdea = new WordItem { WordName = "TestTest" }; 
     //Debug.WriteLine("I'm here!"); 
     //// Add a idea item to the observable collection. 
     //WordItems.Add(newIdea); 

     //// Add a idea item to the local database. 
     //wordsDB.WordItems.InsertOnSubmit(newIdea); 
     WordItem newword = new WordItem { WordName = "Bingo" }; 
     if (WordItems == null) 
     { 
      Debug.WriteLine("I'm null!"); 
      WordItems = new ObservableCollection<WordItem>(); 
     } 

     WordItems.Add(newword); 
     wordsDB.WordItems.InsertOnSubmit(newword); 
     Debug.WriteLine("Did something!"); 
    } 

를 추가하는 버튼이며, 여기에 XAML

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
     <!--<ListBox Margin="14,0,-12,0" FontSize="{StaticResource PhoneFontSizeExtraLarge}" FontFamily="{StaticResource PhoneFontFamilySemiLight}"> 
      <ListBoxItem Content="About" Tap="GoToAbout"/> 
     </ListBox>--> 
     <telerikData:RadJumpList x:Name="TestList" IsStickyHeaderEnabled="True" Margin="14,0,-12,0" ItemsSource="{Binding WordItems}"> 
      <telerikData:RadJumpList.ItemTemplate> 
       <DataTemplate>              
        <StackPanel Orientation="Horizontal" Height="74">          
         <Rectangle x:Name="Bully" Width="20" Fill="Gray" Height="62" VerticalAlignment="Top" HorizontalAlignment="Left" /> 
         <TextBlock Style="{StaticResource PhoneTextExtraLargeStyle}" Text="{Binding WordItem}" VerticalAlignment="Top"/> 
        </StackPanel>       
       </DataTemplate> 
      </telerikData:RadJumpList.ItemTemplate> 

      <telerikData:RadJumpList.StickyHeaderTemplate>      
       <DataTemplate> 
        <Border HorizontalAlignment="Stretch" Background="{StaticResource PhoneBackgroundBrush}" Height="74"> 
         <Border Background="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="62" Height="62"> 
          <TextBlock Text="{Binding}" FontFamily="{StaticResource PhoneFontFamilySemiLight}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Padding="7,0,0,0" VerticalAlignment="Bottom" Foreground="White" /> 
         </Border> 
        </Border> 
       </DataTemplate> 
      </telerikData:RadJumpList.StickyHeaderTemplate> 

      <telerikData:RadJumpList.GroupHeaderTemplate> 
       <DataTemplate> 
        <Border HorizontalAlignment="Stretch" Background="{StaticResource PhoneBackgroundBrush}" Height="74"> 
         <Border Background="{StaticResource PhoneAccentBrush}" VerticalAlignment="Top" HorizontalAlignment="Left" Width="62" Height="62"> 
          <TextBlock Text="{Binding}" FontFamily="{StaticResource PhoneFontFamilySemiLight}" FontSize="{StaticResource PhoneFontSizeExtraLarge}" Padding="7,0,0,0" VerticalAlignment="Bottom" Foreground="White" /> 
         </Border> 
        </Border> 
       </DataTemplate> 
      </telerikData:RadJumpList.GroupHeaderTemplate> 

      <telerikData:RadJumpList.GroupPickerItemsPanel> 
       <ItemsPanelTemplate> 
        <toolkit:WrapPanel HorizontalAlignment="Center" ItemHeight="111" ItemWidth="111"/> 
       </ItemsPanelTemplate> 
      </telerikData:RadJumpList.GroupPickerItemsPanel> 

      <telerikData:RadJumpList.GroupPickerItemTemplate> 
       <DataTemplate> 
        <Border Background="{StaticResource PhoneAccentBrush}" Width="99" Height="99" VerticalAlignment="Top" HorizontalAlignment="Left"> 
         <TextBlock Text="{Binding}" Style="{StaticResource PhoneTextExtraLargeStyle}" VerticalAlignment="Bottom" Foreground="White" /> 
        </Border> 
       </DataTemplate> 
      </telerikData:RadJumpList.GroupPickerItemTemplate> 
     </telerikData:RadJumpList> 
     <Button x:Name="newIdeaAddButton" Click="newIdeaAddButton_Click" Content="Button" Height="72" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="160" /> 
    </Grid> 
+4

정확하게'NullReferenceException'을받는 줄은 무엇입니까? – Spontifixus

+0

이것은 ObservableCollection과는 아무런 관련이 없습니다. 가장 가능성이있는 wordsDB는 null –

+0

입니다. 동의합니다 - wordsDB는 null 일 수 있습니다. –

답변

1
입니다 : 여기 내 관측 모음입니다

오케이, 드디어 도착했습니다. 전자 솔루션! 문제는 그 자체로는 약간 애매합니다. 문제는, 내가 RadJumplist List<strings>에 결합했고이 GroupDescriptor이

GenericGroupDescriptor<string, string> testgroup = new GenericGroupDescriptor<string, string>(listitem => listitem.Substring(0, 1).ToLower()); 

그러나, 문제의 시나리오에 대한 ObservableCollection<WordItem>입니다 따라 정의했다 이전 있다는 것입니다. 항목이 콜렉션에 추가 되 자마자 RadJumpList에 변경 사항이 통지되고 GroupDescriptor가 해당 상황에서 유효하지 않음이 판명됩니다. 그건 어떻게 든 NullReferenceException을 발생시킵니다. 이 오류를 원인과 관련시키는 것은 약간 비현실적입니다.

그래서, 간단한 해결책은

GenericGroupDescriptor<WordItem, string> gengd = new GenericGroupDescriptor<WordItem, string>(); 
     gengd.KeySelector = (WordItem item) => 
      { 
       char keyhead = item.WordName[0]; 
       return keyhead.ToString().ToLower(); 
      }; 

정말 잘 설명하지 않은이 일을 다음과 같이 설명을 변경했습니다!

관련 문제