1 using System; 2 using System.Linq; 3 using System.Reactive.Disposables; 4 using System.Reactive.Linq; 5 using Reactive.Bindings; 6 using Reactive.Bindings.Extensions; 7 using TrainEditor2.Models; 8 using TrainEditor2.Models.Trains; 9 10 namespace TrainEditor2.ViewModels.Trains 11 { 12 internal class TrainViewModel : BaseViewModel 13 { 14 internal ReadOnlyReactivePropertySlim<HandleViewModel> Handle 15 { 16 get; 17 } 18 19 internal ReadOnlyReactivePropertySlim<DeviceViewModel> Device 20 { 21 get; 22 } 23 24 internal ReadOnlyReactivePropertySlim<CabViewModel> Cab 25 { 26 get; 27 } 28 29 internal ReadOnlyReactiveCollection<CarViewModel> Cars 30 { 31 get; 32 } 33 34 internal ReadOnlyReactivePropertySlim<CarViewModel> SelectedCar 35 { 36 get; 37 } 38 39 internal ReadOnlyReactiveCollection<CouplerViewModel> Couplers 40 { 41 get; 42 } 43 44 internal ReadOnlyReactivePropertySlim<CouplerViewModel> SelectedCoupler 45 { 46 get; 47 } 48 TrainViewModel(Train train, App app)49 internal TrainViewModel(Train train, App app) 50 { 51 Handle = train 52 .ObserveProperty(x => x.Handle) 53 .Do(_ => Handle?.Value.Dispose()) 54 .Select(x => new HandleViewModel(x, train)) 55 .ToReadOnlyReactivePropertySlim() 56 .AddTo(disposable); 57 58 Device = train 59 .ObserveProperty(x => x.Device) 60 .Do(_ => Device?.Value.Dispose()) 61 .Select(x => new DeviceViewModel(x, train.Handle)) 62 .ToReadOnlyReactivePropertySlim() 63 .AddTo(disposable); 64 65 Cab = train 66 .ObserveProperty(x => x.Cab) 67 .Do(_ => Cab?.Value.Dispose()) 68 .Select(x => new CabViewModel(x)) 69 .ToReadOnlyReactivePropertySlim() 70 .AddTo(disposable); 71 72 Cars = train.Cars 73 .ToReadOnlyReactiveCollection(x => 74 { 75 MotorCar motorCar = x as MotorCar; 76 TrailerCar trailerCar = x as TrailerCar; 77 78 CarViewModel viewModel = null; 79 80 if (motorCar != null) 81 { 82 viewModel = new MotorCarViewModel(motorCar, train); 83 } 84 85 if (trailerCar != null) 86 { 87 viewModel = new TrailerCarViewModel(trailerCar); 88 } 89 90 return viewModel; 91 }) 92 .AddTo(disposable); 93 94 Couplers = train.Couplers 95 .ToReadOnlyReactiveCollection(x => new CouplerViewModel(x)) 96 .AddTo(disposable); 97 98 SelectedCar = app 99 .ObserveProperty(x => x.SelectedItem) 100 .Where(x => x != null) 101 .Select(x => Cars.FirstOrDefault(y => y.Model == x.Tag)) 102 .ToReadOnlyReactivePropertySlim() 103 .AddTo(disposable); 104 105 SelectedCoupler = app 106 .ObserveProperty(x => x.SelectedItem) 107 .Where(x => x != null) 108 .Select(x => Couplers.FirstOrDefault(y => y.Model == x.Tag)) 109 .ToReadOnlyReactivePropertySlim() 110 .AddTo(disposable); 111 } 112 } 113 } 114