Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 885171
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T12:51:56+00:00 2026-05-15T12:51:56+00:00

I have an object model like this: class Car { public string Manufacturer; public

  • 0

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 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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T12:51:57+00:00Added an answer on May 15, 2026 at 12:51 pm

    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;
    
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an object that looks like this: class Model { public string Category
I have a following model: class Car(models.Model): make = models.CharField(max_length=40) mileage_limit = models.IntegerField() mileage
Hi Suppose I have a simple model class like this: class TestModel(models.Model): testkey =
I have a Django model that looks something like this: class Person(models.Model): name =
I have a complex django object, which has properties of other class types. This
The GoDiagram object model has a GoDocument. GoViews have a reference to a GoDocument.
In my Core Data managed object model, I have an entity Foo with a
I'm relatively new to the Component Object Model specification - I have a simple
I know that the asp.net repeater doesnt have a Client side object model, and
I have a strange behaviour on my Django/PostgreSQL system. After saving a model object

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.