I'm new to stackoverflow. I've been looking for a solution all day long so I decided to ask here.
I'm working on an application which uses WPF and databinding/MVVM. I have a nested ObservableCollection which is part of a Class Program. Both implement INotifyPropertyChange correctly.
In my constructor I create an ObservableColletion of type Program named ListPrograms and fill it from my data service with a list of program. That works all well. Also the binding is working correctly, in my master view I select a program and the nested list of prices is being displayed in the detail view. OnPropertyChange fires correctly for each property of a SalesPrice.
My requirement is that on user input the program needs to recalculate a cummulated price in every line item of the nested list. I have a method which does this correctly.
Im order to run that method I tried to attach a collectionchanged event.
`void GetPrograms()
{
ListPrograms.Clear();
var prgms = DataService.GetProgramList(SearchStringProgram);
ListPrograms=new ObservableCollection<Program>(prgms);
foreach (var prg in ListPrograms)
{
prg.SalesPrices.CollectionChanged+=SalesPrices_CollectionChanged;
} `
///
void SalesPrices_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
foreach (SalesPrice item in e.NewItems)
item.PropertyChanged += SalePrice_PropertyChanged;
if (e.OldItems != null)
foreach (SalesPrice item in e.OldItems)
item.PropertyChanged -= SalePrice_PropertyChanged;
}
void SalePrice_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
RecalcSalePrice(CurrentProgram.SalesPrices);
}
The problem I have is that the collection change event is only registered for new SalesPrices I add to the collections at run time. I check the e.NewStartingIndex and it starts with the number of intial SalesPrice records. (eg. the first program and 9 sales prices it its ObservableColletion and the e.NewStartingIndex has a value of 8). When I add a new record into the list at runtime the even is registering and changes are notified.
I think this is happening because I'm passing the Program object from the dataservice with a filled list of SalesPrices and the event is only registering for new items.
Any idea?
Frank