1 2 3 4 5 6 7 8 9 10 11 12 | < Window x:Class = "WpfApp1.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "" Height = "400" Width = "550" > < DockPanel > < StackPanel DockPanel.Dock = "Bottom" Orientation = "Horizontal" HorizontalAlignment = "Right" > < TextBlock >Total:</ TextBlock > < TextBlock Margin = "30, 0, 0, 0" Text = "{Binding TotalDebit}" /> < TextBlock Margin = "30, 0, 30, 0" Text = "{Binding TotalCredit}" /> </ StackPanel > < DataGrid ItemsSource = "{Binding Items}" /> </ DockPanel > |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Windows; namespace WpfApp1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var r = new Random(); var testData = Enumerable.Range(1, 7).Select(i => new Voucher() { No = 145+i, Date = DateTime.Now.AddDays(r.Next(-5, 5)), Type = (AccountType)r.Next(2), Debit = r.Next(100), Credit = r.Next(100), }); this .DataContext = new Vouchers(testData); } } public class Vouchers : ObservableObject { public Vouchers(IEnumerable<Voucher> items) { Items = new ObservableCollection<Voucher>(items); Items.CollectionChanged += (s, e)=> CalcTotals(); Items.ToList().ForEach(item => item.PropertyChanged += (s, e) => CalcTotals()); CalcTotals(); } public ObservableCollection<Voucher> Items { get ; private set ; } void CalcTotals() { TotalCredit = Items.Sum(x => x.Credit); TotalDebit = Items.Sum(x => x.Debit); } private decimal _totalDebit; public decimal TotalDebit { get { return _totalDebit; } set { _totalDebit = value; OnPropertyChanged( "TotalDebit" ); } } private decimal _totalCredit; public decimal TotalCredit { get { return _totalCredit; } set { _totalCredit = value; OnPropertyChanged( "TotalCredit" ); } } } public enum AccountType { FinancialAccount, OtherAccount } public class Voucher : ObservableObject { public int No { get ; set ; } public DateTime Date { get ; set ; } public AccountType Type { get ; set ; } public string Account { get ; set ; } public string Memo { get ; set ; } private decimal _debit; public decimal Debit { get { return _debit; } set { _debit = value; OnPropertyChanged( "Debit" ); } } private decimal _credit; public decimal Credit { get { return _credit; } set { _credit = value; OnPropertyChanged( "Credit" ); } } } public class ObservableObject : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged( string propertyName) { if (PropertyChanged != null ) PropertyChanged( this , new PropertyChangedEventArgs(propertyName)); } } } |
联系客服