views:

30

answers:

1

Hi everyone,

I have an object model like this:

class Car
{
    public string Manufacturer;
    public int Mileage;
    public ObservableCollection<Part> Parts;
}

class Part
{
    public string Name;
    public int Price;
}

And I want to display the total price of "all my cars" to the user. I want to accomplish this with DataBinding (WPF / Silverlight / XAML). Here's the sort of code I want to write:

class MyWindow : Window
{
    public MyWindow()
    {
        ObservableCollection<Car> myCars = CreateCars();  // Create a collection of cars

        // Let the user edit the collection of Cars
        this.DataGrid.DataContext = myCars;

        // Bind to the grand total Price of all Parts in each Car.
        // Should update text automatically if...
        // 1) The Price of an individual Part changes
        // 2) A Part is added or removed from a Car
        // 3) A Car is added or removed from myCars collection
        this.TotalPriceOfMyCarsLabel.Text = ???  // How?
    }
}

The MVVM approach seem to be the sort of pattern that would be useful here, but I can't figure out the best way to implement it. My object model can be modified, for example, to add INotifyPropertyChanged and such.

The code I've tried to write is in the spirit of http://stackoverflow.com/questions/269073/observablecollection-that-also-monitors-changes-on-the-elements-in-collection but the code gets quite long with all the OnCollectionChanged and OnPropertyChanged eventhandlers flying everywhere.

I'd really like to use DataBinding to handle the calculation and display of the total price, how can I do it in a clean way?

Thanks!

-Mike

+1  A: 

I do strongly recommend MVVM but when it comes to hierarchical models like this, you can save yourself a lot of grief if you're willing and able to make some simple modifications to the model classes themselves.

It can get complicated quickly when you're writing properties and collections that "invalidate" other calculated properties. In my applications, I used an attribute-based approach that lets me decorate a property with a DependsOn attribute so that whenever the dependent property is changed, a property change event is raised for the computed property as well. In your case I don't think you need to go all out like that.

But one thing I think will really come in handy is a class that derives from ObservableCollection which for lack of a better term at the moment I'll call ObservableCollectionEx. The one thing it adds is an ItemPropertyChanged event that lets you hook up one handler to it and it will be raised whenever a property of an item inside the collection changes. This requires you to hook up to INotifyPropertyChanged whenever an item is added or removed. But once this class is out of the way, cascading property changes become a breeze.

I would suggest that you create a CarListViewModel (or whatever you want to call it) that resembles the following. Note that the end result is a hierarchy of objects where any modifications to the read/write Part.Total property results in a chain reaction of PropertyChanged events that bubble up to the ViewModel. The code below is not totally complete. You need to provide an implementation of INotifyPropertyChanged. But at the end you'll see the ObservableCollectionEx I mentioned.

EDIT: I just now clicked the link in your original post and realized you already have an implementation of ObservableCollectionEx. I chose to use the InsertItem, RemoveItem, etc methods instead of OnCollectionChanged to hook/unhook the item event because in the other implementation there's a nasty problem - if you clear the collection, you no longer have the collection of items to unhook.

class CarListViewModel : INotifyPropertyChanged {

    public CarListViewModel() {

        Cars = new ObservableCollectionEx<Car>();
        Cars.CollectionChanged += (sender,e) => OnPropertyChanged("Total");
        Cars.ItemPropertyChanged += (sender,e) => {
            if (e.PropertyName == "Total") {
                OnPropertyChanged("Total");
            }
        }

    }

    public ObservableCollectionEx<Car> Cars {
        get;
        private set;
    }

    public decimal Total {
        get {
            return Cars.Sum(x=>x.Total);
        }
    }

}

class Car : INotifyPropertyChanged {

    public Car() {
        Parts = new ObservableCollectionEx<Part>();
        Parts.CollectionChanged += (sender,e) => OnPropertyChanged("Total");
        Parts.ItemPropertyChanged += (sender,e) => {
            if (e.PropertyName == "Total") {
                OnPropertyChanged("Total");
            }
        }
    }

    public ObservableCollectionEx<Part> Parts {
        get;
        private set;
    }

    public decimal Total {
        get {
            return Parts.Sum(x=>x.Total);
        }
    }

}

class Part : INotifyPropertyChanged {

    private decimal _Total;

    public decimal Total {
        get { return _Total; }
        set {
            _Total = value;
            OnPropertyChanged("Total");
        }
    }

}

class ObservableCollectionEx<T> : ObservableCollection<T> 
    where T: INotifyPropertyChanged
{

    protected override void InsertItem(int index, T item) {
        base.InsertItem(index, item);
        item.PropertyChanged += Item_PropertyChanged;
    }

    protected override void RemoveItem(int index) {
        Items[index].PropertyChanged -= Item_PropertyChanged;
        base.RemoveItem(index);
    }

    protected override void ClearItems() {
        foreach (T item in Items) {
            item.PropertyChanged -= Item_PropertyChanged;
        }
        base.ClearItems();
    }

    protected override void SetItem(int index, T item) {

        T oldItem = Items[index];
        T newItem = item;

        oldItem.PropertyChanged -= Item_PropertyChanged;
        newItem.PropertyChanged += Item_PropertyChanged;

        base.SetItem( index, item );

    }

    private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e) {
        var handler = ItemPropertyChanged;
        if (handler != null) { handler(sender, e); }
    }

    public event PropertyChangedEventHandler ItemPropertyChanged;

}
Josh Einstein