在MVVM Windows Phone 8.1中传播PropertyChanged

时间:2016-04-09 15:52:45

标签: c# mvvm windows-phone-8.1 inotifypropertychanged

我有一个班级:

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;

会做的伎俩但是方法没有被调用(Collection类中的RaisePropertyChanged是!)...

我是MVVM的新手,所以我可能会错过这里显而易见的东西,但我没有看到它。

1 个答案:

答案 0 :(得分:0)

您没有收到PropertyChanged事件,因为它过早被调用。在构建Collection时调用它。您不想知道整个集合实例何时更改,而是在集合中的项目发生更改时。在这种情况下使用此事件

  

Collection.Tracks.CollectionChanged + = OnTracksCollectionChanged;