To achieve this, one could recalculate the total amount each time the total amount has been edited by the user, and each time the product is added or removed from the ObservableCollection .
Since Product implements INotifyPropertyChanged and raises the PropertyChanged event when a new common row is set, ViewModel can handle this event and recalculate the total amount.
ObservableCollection has a CollectionChanged event that occurs when an item is added or removed from it, so the ViewModel can also handle this event and recount. (This part is not needed if the products can be modified and not added / deleted by the user, etc.).
You can try this small program to see how this can be done:
Code for
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;
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>
source share