comparison MetroWpf/Stocks.UI/ViewModels/StocksViewModel.cs @ 23:399398841fd0

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