2012-10-27 40 views
1

我正在爲我的Windows Phone類開發一個程序,並且遇到了一些問題。當我嘗試啓動應用程序時,當試圖訪問靜態ObservableCollection時,我得到一個空引用異常。我認爲這是因爲它是靜態的,我不需要實例化它。我在這裏做錯了什麼?這裏的方法:當訪問靜態ObservableCollection時出現NullReferenceException

protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
{ 
    base.OnNavigatedTo(e); 
    this.DataContext = null; 
    this.DataContext = Settings.NotesList; 
    Settings.CurrentNoteIndex = -1; 
    TheListBox.SelectedIndex = -1; 
    if (Settings.NotesList.Count <= 0) // EXCEPTION 
    { 
     NoteStatus.Visibility = System.Windows.Visibility.Visible; 
     TheListBox.Visibility = System.Windows.Visibility.Collapsed; 
    } 
    else 
    { 
     NoteStatus.Visibility = System.Windows.Visibility.Collapsed; 
     TheListBox.Visibility = System.Windows.Visibility.Visible; 
    } 
} 

凡在一個單獨的文件,我有:

public static class Settings 
{ 
    static Settings() { } 
    public static ObservableCollection<Note> NotesList; 
    static IsolatedStorageSettings settings; 
    private static int currentNoteIndex; 
    public static int CurrentNoteIndex { get; set; } 
} 

我想要寫更多的前測試程序,但我不知道是什麼導致了這一點。 OnNavigatedTo是從啓動應用程序,所以我甚至從來沒有去MainPage.xaml。非常感謝幫助。

+2

爲什麼不做NotesList = new ObservableCollection ()在靜態ctor中? –

+0

完美運作。謝謝,我對C#相當陌生。 – Nathan

+0

因此,它不是您需要實例化的Settings類,而是該類的NotesList屬性。 –

回答

1

即使通過它的靜態,它仍然需要在某處進行實例化。

+0

謝謝,約翰指出我在正確的方向,我在構造函數中實例化它。 – Nathan

+0

@derekwolf我很想知道你是如何在構造函數中實例化靜態類的? – dotNETbeginner

+0

@dotNETbeginner,不,他在靜態構造函數中實例化了一個ObservableCollection。 –

相關問題