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 9252343
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T10:55:17+00:00 2026-06-18T10:55:17+00:00

I have two Classes, one for ViewModel and one for Product . The Product

  • 0

I have two Classes, one for ViewModel and one for Product.
The Product class has a property called Line Total, and the ViewModel Class has a property called Total Amount. The Product class is bound to a DataGrid and the user
inserts the quantity which subsequently and automatically updates the Line Total.

Here is the ViewModel class:

public class ViewModel : INotifyPropertyChanged
{

    public ObservableCollection<Product> products { get; set; }// the children

    private decimal _TotalAmount; 
    public decimal TotalAmount // <=== has to hold sum of [products.LineTotal]
    {
        get
        {
            return totalAmount;
        }
        set
        {
            if (value != _TotalAmount)
            {
                _TotalAmount = value;
                onPropertyChanged(this, "TotalAmount");
            }
        }
    }

Here is the Product class which is a child:

public class Product : INotifyPropertyChanged
    {
        private decimal _LineTotal;
        public decimal LineTotal
        {
            get
            {
                return _LineTotal;
            }
            set
            {
                if (value != _LineTotal)
                {
                    _LineTotal = value;
                    onPropertyChanged(this, "LineTotal");
                }

            }

        }
}

My question is: How the TotalAmount can compute the sum of all Products [Line Total] ? How the child Products can notify the parent ViewModel to update the TotalAmount?

Something like:

foreach(var product in Products)
{
     TotalAmount += product.LineTotal;
}
  • 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-06-18T10:55:18+00:00Added an answer on June 18, 2026 at 10:55 am

    A way to achieve this, would be to recalculate the total amount every time a line total has been edited by the user and every time a product is added or removed from the ObservableCollection.

    Since Product implements INotifyPropertyChanged and raises the PropertyChanged event when a new line total is set, the ViewModel can handle that event and recalculate the total amount.

    ObservableCollection has a CollectionChanged event that is raised when an item is added or removed from it, so the ViewModel can also handle that event and recalculate. (This part is not really necessary if products can only be changed and not added/removed by the user etc.).

    You can try out this small program to see how it could be done:

    Code-behind

    public partial class MainWindow : Window
    {
        ViewModel vm = new ViewModel();
    
        public MainWindow()
        {
            InitializeComponent();
    
            vm.Products = new ObservableCollection<Product>
            {
                new Product { Name = "Product1", LineTotal = 10 },
                new Product { Name = "Product2", LineTotal = 20 },
                new Product { Name = "Product3", LineTotal = 15 }
            };
    
            this.DataContext = vm;
        }
    
        private void AddItem(object sender, RoutedEventArgs e)
        {
            vm.Products.Add(new Product { Name = "Added product", LineTotal = 50 });
        }
    
        private void RemoveItem(object sender, RoutedEventArgs e)
        {
            vm.Products.RemoveAt(0);
        }
    }
    
    public class ViewModel : INotifyPropertyChanged
    {
        private ObservableCollection<Product> _products;
        public ObservableCollection<Product> Products
        {
            get { return _products; }
            set
            {
                _products = value;
    
                // We need to know when the ObservableCollection has changed.
                // On added products: hook up eventhandlers to their PropertyChanged events.
                // On removed products: recalculate the total.
                _products.CollectionChanged += (sender, e) =>
                {
                    if (e.NewItems != null)
                        AttachProductChangedEventHandler(e.NewItems.Cast<Product>());
                    else if (e.OldItems != null)
                        CalculateTotalAmount();
                };
    
                AttachProductChangedEventHandler(_products);
            }
        }
    
        private void AttachProductChangedEventHandler(IEnumerable<Product> products)
        {
            // Attach eventhandler for each products PropertyChanged event.
            // When the LineTotal property has changed, recalculate the total.
            foreach (var p in products)
            {
                p.PropertyChanged += (sender, e) =>
                {
                    if (e.PropertyName == "LineTotal")
                        CalculateTotalAmount();
                };
            }
    
            CalculateTotalAmount();
        }
    
        public void CalculateTotalAmount()
        {
            // Set TotalAmount property to the sum of all line totals.
            TotalAmount = Products.Sum(p => p.LineTotal);
        }
    
        private decimal _TotalAmount;
        public decimal TotalAmount
        {
            get { return _TotalAmount; }
            set
            {
                if (value != _TotalAmount)
                {
                    _TotalAmount = value;
    
                    if (PropertyChanged != null)
                        PropertyChanged(this, new PropertyChangedEventArgs("TotalAmount"));
                }
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    }
    
    public class Product : INotifyPropertyChanged
    {
        public string Name { get; set; }
    
        private decimal _LineTotal;
        public decimal LineTotal
        {
            get { return _LineTotal; }
            set
            {
                if (value != _LineTotal)
                {
                    _LineTotal = value;
    
                    if (PropertyChanged != null)
                        PropertyChanged(this, new PropertyChangedEventArgs("LineTotal"));
                }
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    }
    

    XAML:

    <Window x:Class="WpfApplication3.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <StackPanel>
            <DataGrid ItemsSource="{Binding Products}" AutoGenerateColumns="False">
                <DataGrid.Columns>
                    <DataGridTextColumn Binding="{Binding Name}" />
                    <DataGridTextColumn Binding="{Binding LineTotal}" />
                </DataGrid.Columns>
            </DataGrid>
    
            <Button Click="AddItem">Add item</Button>
            <Button Click="RemoveItem">Remove item</Button>
    
            <TextBlock>
                <Run>Total amount:</Run>
                <Run Text="{Binding TotalAmount}" />
            </TextBlock>
        </StackPanel>
    </Window>
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have two classes. One class has a variable Image plane = null; in
I have two classes, one nested in the other. Public Class Operation Public Property
I have two classes (MVC view model) which inherits from one abstract base class.
I have two classes, one that inherits from the other. The base class is
I have two (unrelated) classes. The first one is Point: typedef std::complex<double> complex_number; class
I have the following two classes, one inherits from the other Class A{ void
I have two ViewModel classes : PersonViewModel and PersonSearchListViewModel. One of the fields PersonViewModel
Lets say I have two classes one base class: public class BaseModel { }
I have two classes, one depends on another. It is implemented like this: class
I have two viewmodel classes called ChangePwdViewModel.cs and ExpiringPwdViewModel.cs . ChangPwd.xaml binds to ChangePwdViewModel

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.