Hi All, I have a observable collection of viewmodel objects. How can I subscribe to the Property Changed event of each view model in my collection as they are created and track which ones have been changed, so that I can updated them to my database.
+2
A:
I believe that the code below serves as an example of how to solve your problem. In this example MyCollection is a property ViewModel objects. ViewModel implements the INotifyPropertyChanged interface.
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;
}
}
Tony Borres
2010-04-28 20:32:15
I have edited the code to show the way I laod my data. Is it possible to know the updates on the objects, not the adding and removal of objects..
developer
2010-04-28 20:42:34
The viewModel_PropertyChanged handler will be called any time a property on a ViewModel changes (any property that raises the PropertyChanged event). Generally you would add a switch statement that switches on the e.PropertyName. I've updated the code to show an example where MyPropertyName is a property that exists on one or more of the ViewModels.
Tony Borres
2010-04-29 20:46:12
Thank you soooo much..
developer
2010-04-29 20:51:03