I have data saved in the IsolatedStorage in my WP7 app, this data is a ObservableCollection
I then load the data into a observablecollection in the app that is databinded to a listview with a datatemplate
But when I do this (Or just add data to the databound list) in the constructor it fires a ListBox selectionchanged event, so before my app is fully loaded this happens.
I have an event for selectionchanged to show details about the clicked object and this crashes when this happens (Selectedindex is 0 for some reason so object 1 in the loaded list is selected automaticly when loaded)
public partial class MainPage : INotifyPropertyChanged
{
public ObservableCollection<Note> NotesCollection { get; set; }
public CollectionViewSource NotesViewSource;
private readonly IsolatedStorageSettings settings;
// Constructor
public MainPage()
{
InitializeComponent();
NotesCollection = new ObservableCollection<Note>();
settings = IsolatedStorageSettings.ApplicationSettings;
if (settings.Contains("Notes"))
{
NotesCollection = (ObservableCollection<Note>)settings["Notes"];
}
else
{
settings.Add("Notes", NotesCollection);
}
NotesViewSource.View.Refresh();
//var note = new Note("hej", "hej", DateTime.Now, DateTime.Now);
//NotesCollection.Add(note); this also fires the event
NotesViewSource = new CollectionViewSource { Source = NotesCollection };
DataContext = this;
ListBoxNotes.ItemsSource = NotesViewSource.View;
}
my Selectionchanged
private void ListBoxNotesSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (ListBoxNotes.SelectedIndex == -1)
return;
var note = ListBoxNotes.SelectedItem as Note;
if (!(note is Note)) return;
(Application.Current as App).Note = note;
ListBoxNotes.SelectedIndex = -1;
NavigationService.Navigate(new Uri("/Views/DetailsView.xaml", UriKind.Relative));
}
If you want to add items to the OC before any bindings may fire, then move the following line
after the point where items are added. When this method is called, all the UI is created and bindings are set. You can right-click and go to definition to see it happening.