2016-04-09 62 views
0

我有一個類:傳播的PropertyChanged在MVVM的Windows Phone 8.1

public class Collection : INotifyPropertyChanged 
{ 
    public Collection() 
    { 
     this.tracks = new ObservableCollection<Track>(); 
    } 

    public void addTrack(Track track) 
    { 
     if (this.tracks.Contains(track)) return; 

     this.tracks.Add(track); 
     RaisePropertyChanged("tracks"); 
    } 

    public ObservableCollection<Track> tracks 
    { 
     get 
     { 
      return _tracks; 
     } 
     set 
     { 
      if (_tracks != value) 
      { 
       _tracks = value; 
       RaisePropertyChanged("tracks"); 
      } 
     } 
    } 
    private ObservableCollection<Track> _tracks; 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void RaisePropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
      this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

而且一個ViewModel:

public class ScanningPageViewModel : ViewModelBase 
{ 
    private INavigationService navigationService; 

    public ScanningPageViewModel(INavigationService navigationService) 
    { 
     App.Collection.PropertyChanged += Collection_PropertyChanged; 

     this.navigationService = navigationService; 
     this.LoadData(); 
    } 

    private async void LoadData() 
    { 
     await CollectionService.PopulateCollection(); 
     this.navigationService.NavigateTo("MainPage"); 
    } 

    public int CollectionCount 
    { 
     get 
     { 
      return App.Collection.tracks.Count; 
     } 
    } 

    public void Collection_PropertyChanged(object sender, PropertyChangedEventArgs e) 
    { 
     RaisePropertyChanged("CollectionCount"); 
    } 
} 

基本上我想提出一個屬性更改爲 「CollectionCount」 每次我收集的變化。

我本來以爲

App.Collection.PropertyChanged += Collection_PropertyChanged; 

會做的伎倆,但該方法沒有得到所謂的(在集合類RaisePropertyChanged的!)......

我是新與MVVM所以我可能會錯過這裏顯而易見的東西,但我沒有看到它。

+1

您是否嘗試過調試您的應用程序?你確定'App.Collection.PropertyChanged + = Collection_PropertyChanged;'中的集合是後來被更改的同一個集合嗎?如果是這樣,那麼再次檢查它的'PropertyChanged'調用列表中有'Collection_PropertyChanged'事件處理程序,並且'this.PropertyChanged(this,New PropertyChangedEventArgs(propertyName));'實際上被調用。 –

+0

你是對的,我再次初始化App.Collection,以便ViewModel不再指向正確的Collection實例。 –

回答

0

您沒有得到PropertyChanged事件,因爲它調用得太早。它在集合構建時調用。您不想知道整個集合實例何時發生更改,而是什麼時候集合中的項目發生更改。在這種情況下使用此事件

Collection.Tracks.CollectionChanged + = OnTracksCollectionChanged;

相關問題