comparison MetroWpf/Stocks.UI/StocksViewModel.cs @ 20:6109bc268b90

Latest
author adminsh@apollo
date Tue, 20 Mar 2012 13:37:46 +0000
parents
children
comparison
equal deleted inserted replaced
19:09d18d6e5f40 20:6109bc268b90
1 using System;
2 using System.ComponentModel;
3 using System.Linq;
4 using System.Reactive;
5 using System.Reactive.Linq;
6 using System.Windows.Input;
7 using GalaSoft.MvvmLight;
8 using GalaSoft.MvvmLight.Command;
9 using Stocks.Common;
10 using Stocks.Common.Events;
11
12 namespace Stocks.UI
13 {
14 public class StocksViewModel : ViewModelBase
15 {
16 private readonly IStocksService _service;
17
18 public BindingList<DisplayStockPrice> DisplayStockPrices { get; set; }
19 public ICommand ServiceCommand { get; set; }
20 public ICommand SubscriptionCommand { get; set; }
21
22 public StocksViewModel(IStocksService service)
23 {
24 _service = service;
25 GetLatestPrices();
26
27 SubscriptionCommand = new RelayCommand(SubscriptionCommandExecute);
28 ServiceCommand = new RelayCommand(ServiceRunningCommandExecute);
29
30 var priceUpdates = Observable.FromEventPattern<PriceChangedEventArgs>(
31 _service, "PriceChanged");
32
33 priceUpdates.Where(e => Subscribed)
34 //.Throttle(TimeSpan.FromSeconds(1))
35 .Subscribe(PriceChanged);
36 }
37
38 public void PriceChanged(EventPattern<PriceChangedEventArgs> e)
39 {
40 var displayRate = DisplayStockPrices.First(
41 rate => rate.Symbol == e.EventArgs.Price.Symbol);
42
43 if (displayRate != null)
44 displayRate.Update(e.EventArgs.Price);
45 }
46
47
48 private void GetLatestPrices()
49 {
50 DisplayStockPrices = new BindingList<DisplayStockPrice>();
51 var currentRates = _service.GetFullCurrentPrices();
52 foreach (var latestRate in currentRates)
53 {
54 var displayRate = DisplayStockPrice.Create(latestRate);
55 DisplayStockPrices.Add(displayRate);
56 }
57 }
58
59 private const string SubscribedPropertyName = "Subscribed";
60 private bool _subscribed = false;
61
62 public bool Subscribed
63 {
64 get { return _subscribed; }
65 set
66 {
67 if (_subscribed == value) return;
68 _subscribed = value;
69 RaisePropertyChanged(SubscribedPropertyName);
70 }
71 }
72
73 private const string ServiceRunningPropertyName = "ServiceRunning";
74 private bool _serviceRunning;
75
76 public bool ServiceRunning
77 {
78 get { return _serviceRunning; }
79 set
80 {
81 if (_serviceRunning == value) return;
82 _serviceRunning = value;
83 RaisePropertyChanged(ServiceRunningPropertyName);
84 }
85 }
86
87 private void ServiceRunningCommandExecute()
88 {
89 if (_service.IsRunning)
90 {
91 _service.Stop();
92 ServiceRunning = false;
93 }
94 else
95 {
96 _service.Start();
97 ServiceRunning = true;
98 }
99 }
100
101 private void SubscriptionCommandExecute()
102 {
103 //toggle subscribed
104 Subscribed = !Subscribed;
105 }
106 }
107 }