2012-01-09 102 views
1

我在WP7應用程序保存在IsolatedStorage數據,這個數據是一個的ObservableCollection的ObservableCollection <T>火災SelectionChanged事件

那麼我將數據加載到應用程序一個的ObservableCollection是databinded到listview與數據模式

但是,當我這樣做(或只是將數據添加到數據綁定列表)在構造它觸發ListBox selectionchanged事件,所以在我的應用程序完全加載之前,會發生這種情況。

我對的SelectionChanged以顯示有關所點擊對象的詳細信息的事件和此崩潰發生這種情況時(的SelectedIndex是0爲某種原因使在加載的列表對象1加載時,全自動選擇)

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; 
    } 

我的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)); 
    } 
+2

問題是什麼? – 2012-01-09 20:34:28

+0

拋出什麼異常? – 2012-01-09 21:28:02

回答

4

如果你想項添加到OC任何綁定可能火中,然後將下面的行

InitializeComponent(); 

後,其中加入項目點。當調用此方法時,將創建所有UI並設置綁定。您可以右鍵單擊並轉到定義以查看發生的情況。

1

我會連接到Loaded事件。

使用私人和公共。注意私人小寫字母。

private ObservableCollection<Note> notesCollection 

使SelectedIndex成爲公共屬性並綁定到它。 當您分配私人側設置爲-1;

private int selectedIndex = -1; 

默認情況下,選定的索引是0.並且選擇的索引更改始終會在應用程序啓動時觸發。您只需在調用事件之前設置selectedIndex = -1。

SelectedIndex作爲公共屬性我會做集合中的邏輯,甚至沒有更改的事件。

+0

如果我不從獨立存儲或我創建的2個調試行加載數據,那麼事件不會被觸發。如果我在應用程序運行時添加數據,那麼neihten – Mech0z 2012-01-09 21:37:19

+0

如果沒有任何限制,那麼甚至不會觸發 - 這應該不是什麼大驚喜。至於添加不改變選定索引的數據,那麼你爲什麼期望它被觸發?在事件觸發之前,我沒有回答您如何將選定索引指定爲-1的問題嗎?那不是你的問題嗎?如果這不是你的問題,那麼問題是什麼? – Paparazzi 2012-01-09 22:00:33