I am having trouble using the Add method for an ObservableCollection to simply add a new string value to the observablecollection upon a click event. I create my ObservableCollection in a Settings.cs class and then reference that observablecollection throughout multiple pages in my wp7.1 project. This system has worked perfectly for when I need to add several items of one observablecollection to another, either setting one equal to the other or using .Union depending on the purpose needed. In this case though, I am attempting to add a single string item to my ObservableCollection of type string. My code is as follows
Settings.cs
public static Setting<ObservableCollection<string>> Favorites = new Setting<ObservableCollection<string>>("Favorites", null);
Favorites.xaml
<ListBox x:Name="FavoritesListBox" Grid.Row="1" ItemsSource="{Binding}" Margin="12,0,12,0"
SelectionChanged="FavoritesListBox_SelectionChanged">
FavoritesPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string favorUrl = null;
NavigationContext.QueryString.TryGetValue("curUrl", out favorUrl);
if (favorUrl != null )
{
//This works but the FavoritesListBox items are cleared upon new page navigation or closing
//this.FavoritesListBox.Items.Add(favorUrl);
//This does not work!?
//if (Settings.Favorites.Value == null)
//{
// //Settings.Favorites.Value.Add(favorUrl);
//}
//else
//{
// Settings.Favorites.Value.Add(favorUrl);
//}
}
//base.OnNavigatedTo(e);
}
private void FavoritesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.NavigationService.Navigate(new Uri("/MainPage.xaml?favUrl=" + e.AddedItems[0], UriKind.Relative));
}
using the .Add method in FavoritesPage.xaml.cs does not give me any coding errors but when debugging I get a NullReferenceException. I also tried using .Insert and that did not work either. Please help this seems to be an easy fix but I have not been able to figure this out! Thanks in advance!
You’re referencing a
nullobject after confirming that it isnull!You need to do this:
Alternately, you can change the initialization from
to
This way you can avoid the
nullcheck.