Instead of mixing everything together you need two classes.
public class ParagonClass : INotifyPropertyChanged
{
//some variables
private decimal _totalValue;
public decimal TotalValue
{
get
{
if (ProductID > 0)
_totalValue = Math.Round(ProductCount * PriceBrutto, 2, MidpointRounding.AwayFromZero);
return _totalValue;
}
// No need for a setter if its calculated
// See Sheridan's answer for how to do this
// set
// {
// _totalValue = value;
// NotifyPropertyChanged("TotalValue");
// }
}
...
}
And a collection
public class ParagonCollection : ObservableCollection<ParagonClass>, INotifyPropertyChanged
{
private int sum;
public int Sum
{
get{ return sum;}
set
{
sum = value;
NotifyPropertyChanged("Sum");
}
}
// You'll need as implantation of INotifyPropertyChanged here
// and some extra stuff to come
...
}
Now we just need to calculate the sum whenever the it changes. There are several times this occurs
- When a new Paragon is added to the collection
- When a Paragon changes
Lets take them one at a time, and we can hook up the Paragon items being added via the collection by listening for collection changes in the constructor
public ParagonCollection()
{
// When the collection changes set the Sum to the new Sum of TotalValues
this.CollectionChanged += OnCollectionChanged;
}
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs notifyCollectionChangedEventArgs)
{
Recalculate();
}
private void Recalculate()
{
Sum = this.Sum(x=>x.TotalValue);
}
Now if you design your ParagonClass
so that the items are immutable (i.e they don't change after they have been created), then you should be all done. However if you need your Paragons to change we need to rewrite what happens when we add or remove an item
private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args)
{
foreach(ParagonClass item in args.OldItems)
{
// Unsubscribe to changes in each item
item.PropertyChanged -= OnItemChanged;
}
foreach(ParagonClass item in args.NewItems)
{
// Subscribe to future changes for each item
item.PropertyChanged += OnItemChanged;
}
Recalculate();
}
private void OnItemChanged(object sender, PropertyChangedEventArgs args)
{
Recalulate();
// You might decide that you only want to recalculate for some property
// changes, and do something like the following instead
// if (args.PropertyName=="TotalValue")
// Recalulate();
}