ObservableCollection中ViewModel的PropertyChanged事件

时间:2010-04-28 19:56:50

标签: wpf observablecollection

我有一个可观察的viewmodel对象集合。如何在创建集合时订阅我的集合中每个视图模型的Property Changed事件,并跟踪哪些已更改,以便我可以将它们更新到我的数据库。

1 个答案:

答案 0 :(得分:2)

我相信下面的代码可以作为解决问题的一个例子。在此示例中,MyCollection是一个属性ViewModel对象。 ViewModel实现了INotifyPropertyChanged接口。

private void AddCollectionListener()
    {
        if (MyCollection != null)
        {
            MyCollection.CollectionChanged += 
                new System.Collections.Specialized.NotifyCollectionChangedEventHandler(MyCollection_CollectionChanged);
        }
    }

    void MyCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        // Remove Listeners to each item that has been removed
        foreach (object oldItem in e.OldItems)
        {
            ViewModel viewModel = oldItem as ViewModel;

            if (viewModel != null)
            {
                viewModel.PropertyChanged -= viewModel_PropertyChanged;
            }
        }

        // Add Listeners to each item that has been added
        foreach (object newItem in e.NewItems)
        {
            ViewModel viewModel = newItem as ViewModel;

            if (viewModel != null)
            {
                viewModel.PropertyChanged += new PropertyChangedEventHandler(viewModel_PropertyChanged);
            }
        }
    }

    void viewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        // TODO: Property Changed Logic

        switch (e.PropertyName)
        {
            case "MyPropertyName":
                // TODO: Perform logic necessary when MyPropertyName changes
                break;
            default:
                // TODO: Perform logic for all other property changes.
                break;
        }
    }