Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Collections.Specialized;
- using System.ComponentModel;
- using System.Data.Entity;
- using System.Linq;
- using System.Windows.Controls;
- using DbContext;
- using GalaSoft.MvvmLight.Command;
- using GalaSoft.MvvmLight.Messaging;
- using SalesApp.Logic.Ui.Model;
- namespace SalesApp.Logic.Ui.ViewModel
- {
- public class OrderViewModel : ViewModelBase
- {
- private decimal _totalPrice;
- public decimal TotalPrice
- {
- get => this._totalPrice;
- set
- {
- if (this._totalPrice == value)
- return;
- this._totalPrice = value;
- RaisePropertyChanged();
- }
- }
- private ObservableCollection<Product> _products;
- public ObservableCollection<Product> Products
- {
- get => this._products;
- set
- {
- if (this.Products != null)
- {
- this.Products.CollectionChanged -= OnCollectionChanged;
- UnsubscribeFromItemPropertyChanged(this.Products);
- }
- if (this.Products == value)
- return;
- this._products = value;
- this.Products.CollectionChanged += OnCollectionChanged;
- if (this.Products.Any())
- {
- SubscribeToItemPropertyChanged(this.Products);
- }
- RaisePropertyChanged();
- }
- }
- private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
- {
- if (e.Action.Equals(NotifyCollectionChangedAction.Reset))
- {
- UnsubscribeFromItemPropertyChanged(sender as IEnumerable);
- return;
- }
- if (!e.Action.Equals(NotifyCollectionChangedAction.Move))
- {
- UnsubscribeFromItemPropertyChanged(e.OldItems);
- SubscribeToItemPropertyChanged(e.NewItems);
- }
- CalculateTotalPrice();
- }
- private void ProductChanged(object sender, PropertyChangedEventArgs e) => CalculateTotalPrice();
- private void SubscribeToItemPropertyChanged(IEnumerable newItems)
- {
- if (newItems != null)
- {
- foreach (INotifyPropertyChanged item in newItems.OfType<INotifyPropertyChanged>())
- item.PropertyChanged += ProductChanged;
- }
- }
- private void UnsubscribeFromItemPropertyChanged(IEnumerable oldItems)
- {
- if (oldItems != null)
- {
- foreach (INotifyPropertyChanged item in oldItems.OfType<INotifyPropertyChanged>())
- item.PropertyChanged -= ProductChanged;
- }
- }
- private void CalculateTotalPrice() => this.TotalPrice = this.Products.Sum(item => item.total_price);
- private void GetProducts()
- {
- using (var context = new mainEntities())
- {
- var result = context.product.Include(c => c.brand);
- this.Products = new ObservableCollection<Product>(
- result.Select(item => new Product(item.name, item.mass, item.ean, item.brand.name, item.price)));
- }
- }
- public OrderViewModel()
- {
- SetView("Dodaj zamówienie");
- GetProducts();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement