本文整理汇总了C#中ReactiveCommand.Select方法的典型用法代码示例。如果您正苦于以下问题:C# ReactiveCommand.Select方法的具体用法?C# ReactiveCommand.Select怎么用?C# ReactiveCommand.Select使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ReactiveCommand
的用法示例。
在下文中一共展示了ReactiveCommand.Select方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: PostListViewModel
public PostListViewModel()
{
service = new PostService();
var filters = MessageBus.Current.Listen<PostFilter>(MessageTypes.CurrentPostFilter)
.Throttle(TimeSpan.FromSeconds(0.7), RxApp.DeferredScheduler);
var refreshRequests = new ReactiveCommand();
GlobalCommands.RefreshCommand.RegisterCommand(refreshRequests);
var filtersToRefresh = refreshRequests
.Select((_, i) => i)
.CombineLatest(filters, (i, f) => new {CommandId = i, Filter = f})
.DistinctUntilChanged(x => x.CommandId)
.Select(x => x.Filter);
var results = filters.Merge(filtersToRefresh)
.ObserveOn(RxApp.TaskpoolScheduler)
.Select(x => new { TargetFilter = x, Value = service.GetPosts(x) });
var latestResults = filters
.CombineLatest(results, (f, r) => new { LatestFilter = f, LatestResult = r })
.Where(x => Equals(x.LatestFilter, x.LatestResult.TargetFilter))
.Select(x => x.LatestResult);
latestResults
.Select(x => x.Value.Select(p => new PostViewModel
{
Title = p.Title,
FeedName = p.FeedName,
FeedImage = new Uri(p.FeedImage),
PublicationDate = p.PublicationDate
}).ToList())
.ToProperty(this, x => x.Posts);
}
示例2: TestPage1ViewModel
public TestPage1ViewModel(IScreen screen = null)
{
HostScreen = screen;
RandomGuid = Guid.NewGuid();
// XXX: This is hella jank
NavPage2 = new ReactiveCommand(screen.Router.Navigate.CanExecuteObservable);
NavPage2.Select(_ => new TestPage2ViewModel(screen)).InvokeCommand(screen.Router.Navigate);
NavPage3 = new ReactiveCommand(screen.Router.Navigate.CanExecuteObservable);
NavPage3.Select(_ => new TestPage3ViewModel(screen)).InvokeCommand(screen.Router.Navigate);
}
示例3: ToastViewModel
public ToastViewModel(ShowToastMessage showToastMessage, IChatDocument document, IMessageBus bus, IApplicationActivator activator)
{
_document = document;
_document.FontSize = 14;
IsVisible = true;
RoomName = showToastMessage.Message.Room.Name;
_document.AddMessage(showToastMessage.Message.Message, showToastMessage.Message.User, null);
CloseCommand = new ReactiveCommand();
ActivateCommand = new ReactiveCommand();
Closed = Observable.Timer(TimeSpan.FromSeconds(showToastMessage.Action.SecondsVisible), RxApp.TaskpoolScheduler)
.Do(_ => IsClosing = true).Delay(TimeSpan.FromSeconds(2), RxApp.TaskpoolScheduler)
.Select(_ => Unit.Default)
.Merge(CloseCommand.Select(_ => Unit.Default))
.Merge(ActivateCommand.Select(_ => Unit.Default));
Subscribe(() =>bus.RegisterMessageSource(
ActivateCommand.Select(
_ => new ActivateModuleByIdMessage(ModuleNames.MainCampfireView, showToastMessage.Message.Room.Id))
.Do(_ => activator.Activate())));
}
示例4: ChangesetViewModel
public ChangesetViewModel(IApplicationService applicationService)
{
_applicationService = applicationService;
Comments = new ReactiveCollection<CommentModel>();
GoToHtmlUrlCommand = new ReactiveCommand(this.WhenAnyValue(x => x.Commit, x => x != null));
GoToHtmlUrlCommand.Select(x => Commit).Subscribe(GoToUrlCommand.ExecuteIfCan);
GoToRepositoryCommand = new ReactiveCommand();
GoToRepositoryCommand.Subscribe(_ =>
{
var vm = CreateViewModel<RepositoryViewModel>();
vm.RepositoryOwner = RepositoryOwner;
vm.RepositoryName = RepositoryName;
ShowViewModel(vm);
});
GoToFileCommand = new ReactiveCommand();
GoToFileCommand.OfType<CommitModel.CommitFileModel>().Subscribe(x =>
{
if (x.Patch == null)
{
var vm = CreateViewModel<SourceViewModel>();
// vm.GitUrl = x.ContentsUrl;
// vm.HtmlUrl = x.BlobUrl;
// vm.Name = x.Filename;
// vm.Path = x.Filename;
// vm.ForceBinary = true;
ShowViewModel(vm);
}
else
{
var vm = CreateViewModel<ChangesetDiffViewModel>();
vm.Username = RepositoryOwner;
vm.Repository = RepositoryName;
vm.Branch = Commit.Sha;
vm.HtmlUrl = x.BlobUrl;
ShowViewModel(vm);
}
});
LoadCommand.RegisterAsyncTask(t =>
{
var forceCacheInvalidation = t as bool?;
var t1 = this.RequestModel(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Get(), forceCacheInvalidation, response => Commit = response.Data);
Comments.SimpleCollectionLoad(_applicationService.Client.Users[RepositoryOwner].Repositories[RepositoryName].Commits[Node].Comments.GetAll(), forceCacheInvalidation).FireAndForget();
return t1;
});
}
示例5: NavigationContentViewModel
public NavigationContentViewModel(ISettingsViewModel settingsViewModel, IMessageBus bus)
{
_settingsViewModel = settingsViewModel;
bus.Listen<AppUpdateAvailableMessage>().SubscribeOnceUI(_ =>
{
ShowUpdate = true;
});
bus.Listen<AppUpdateProgressMessage>().SubscribeUI(msg =>
{
ShowProgress = true;
ShowUpdate = false;
ProgressValue = msg.ProgressPercentage;
});
StartUpdateCommand = new ReactiveCommand();
bus.RegisterMessageSource(StartUpdateCommand.Select(c => new RequestAppUpdateMessage()));
}
示例6: SynchronizeObjectViewModel
public SynchronizeObjectViewModel()
{
var inpc = new ObservableObject { Name = "Bill" };
var poco = new PlainObject { Name = "Steve" };
// TwoWay synchronize
TwoWay = inpc.ToReactivePropertyAsSynchronized(x => x.Name);
// OneWay synchronize
OneWay = inpc.ObserveProperty(x => x.Name).ToReactiveProperty();
// OneWayToSource synchronize
OneWayToSource = ReactiveProperty.FromObject(poco, x => x.Name);
// synchronization check
CheckCommand = new ReactiveCommand();
this.AlertMessage = CheckCommand.Select(_ =>
"INPC Name:" + inpc.Name + Environment.NewLine
+ "POCO Name:" + poco.Name)
.ToReactiveProperty(mode: ReactivePropertyMode.None);
}
示例7: AppViewModel
public AppViewModel(ReactiveCommand<Object> testExecuteSearchCommand = null, IObservable<ObservableCollection<FlickrPhoto>> testSearchResult = null)
{
ExecuteSearch = testExecuteSearchCommand ?? ReactiveCommand.Create();
LoadMoreItems = ReactiveCommand.Create();
this.ObservableForProperty(x => x.SearchTerm)
.Throttle(TimeSpan.FromMilliseconds(800), RxApp.TaskpoolScheduler)
.Select(x => x.Value)
.DistinctUntilChanged()
.Where(x => !String.IsNullOrWhiteSpace(x))
.InvokeCommand(ExecuteSearch);
_spinnerVisibility = ExecuteSearch.IsExecuting
.Select(x => x ? Visibility.Visible : Visibility.Collapsed)
.ToProperty(this, x => x.SpinnerVisibility, Visibility.Hidden);
IObservable<ObservableCollection<FlickrPhoto>> results;
if (testSearchResult != null)
results = testSearchResult;
else
results = ExecuteSearch.Select(term => GetSearchResultFromBing((string)term));
_searchResults = results.ToProperty(this, x => x.SearchResults, new ObservableCollection<FlickrPhoto>());
LoadMoreItems
.Select(x => LoadMore((int)x))
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(x =>
{
foreach (var item in x)
{
SearchResults.Add(item);
}
});
SearchTerm = "british cat";
}
示例8: BlockTimerViewModel
public BlockTimerViewModel(BlockItem Model)
{
this.Model = Model;
// Complete the TimerState when the break finishes
// When the TimerState ends (i.e. the dialog is closed), set the
// EndedAt time.
//
// Note that it's really important that whenever you use any
// time-based Rx operator like Timer or Delay, that you use an
// RxApp-based scheduler. If you don't do this (and it's really easy
// to forget!), your unit tests won't work properly!
var timer = Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds(1.0), RxApp.DeferredScheduler)
.TakeWhile(_ => !isFinishedWithBreak())
.Finally(() => {
this.Model.EndedAt = RxApp.DeferredScheduler.Now;
_TimerState.OnCompleted();
});
// COOLSTUFF: Defining a Command-based State Machine
//
// Here, we're creating our Commands - let's look a bit further into
// how this actually works. Looking back to our problem definition,
// we can see that many of these buttons' CanExecute() are tied to
// each other (i.e. Hitting Pause means I can't hit it again until I
// hit Start).
//
// Here, we're defining the conditions when each of these buttons
// are allowed to be clicked. In the next block, we convert each of
// the Execute() Observables (each command is an Observable who
// fires whenever it is Executed), into the state that we *should*
// move to once the button is hit. We then subscribe to it, and move
// to the new state.
// Define when we can click each of these commands
Start = new ReactiveCommand(
_TimerState.Select(x => x == BlockTimerViewState.Initialized || x == BlockTimerViewState.Paused));
Pause = new ReactiveCommand(
_TimerState.Select(x => x == BlockTimerViewState.Started || x == BlockTimerViewState.StartedInBreak));
Cancel = new ReactiveCommand(
_TimerState.Select(x => x != BlockTimerViewState.Initialized));
// Move to the next state appropriately when the Start, Pause, and Cancel buttons are clicked
Observable.Merge(
Start.Select(_ => isInBreak() ? BlockTimerViewState.StartedInBreak : BlockTimerViewState.Started),
Pause.Select(_ => BlockTimerViewState.Paused),
Cancel.Select(_ => BlockTimerViewState.ShouldCancel)
).Subscribe(_TimerState.OnNext);
// Set the StartedAt time on the Model when we click the Start
// button. It's also important here to use RxApp's Now instead of
// DateTime.Now, or else our tests will be very confused.
Start.Subscribe(_ => this.Model.StartedAt = this.Model.StartedAt ?? RxApp.DeferredScheduler.Now);
// Create an Observable who yields the current State whenever the
// timer fires - it has the Rate of the Timer but the Value of the
// TimerState.
var timerAsState = timer.CombineLatest(_TimerState, (_, ts) => ts);
// Take the timer and derive a version that only notifies us when
// the TimerState has changed
var distinctTimerAsState = timerAsState.DistinctUntilChanged();
// Invalidate the object when they hit Cancel
Cancel.Subscribe(x => {
Model.StartedAt = null; Model.EndedAt = null;
});
// When someone hits the Start button, then Pause, then the Start
// button, we create a record of how long they pause.
//
// This code is a bit tricky - the key is BufferWithCount; if we
// have a sequence [1,2,3,4,5], BufferWithCount(3,1) will return:
// [[1,2,3], [2,3,4], [3,4,5], ...]: advancing forward one at a
// time, returning the last three items. This is important, since
// we're looking for the pattern, "Start, Pause, Start"
//
// Also, we again see here, whenever we use a Time-based operator
// like Timestamp, that we use an RxApp scheduler. This is a very
// common yet annoying-to-debug mistake!
distinctTimerAsState
.Timestamp(RxApp.DeferredScheduler)
.Buffer(3 /*items in buffer*/, 1 /*at a time*/)
.Where(isStateSequenceAPause)
.Subscribe(x => this.Model.AddRecordOfPause(new PauseRecord() {
StartedAt = x[1].Timestamp,
EndedAt = x[2].Timestamp,
}));
// Move to the Break when the normal timer expires
timerAsState
.Where(ts => isInBreak() && ts == BlockTimerViewState.Started)
.Subscribe(_ => _TimerState.OnNext(BlockTimerViewState.StartedInBreak));
/* COOLSTUFF: Superpowered Value Converters
*
* Here we're binding the application state Observables we've
* created above into real WPF properties that we can bind to (since
* WPF can't bind directly to Observables). However, unlike
* IValueConverters which are very simple, we can do much more
//.........这里部分代码省略.........
示例9: ViewMapVM
public ViewMapVM(
IMapStorageService MapStorage,
ILocationService Location,
IFieldDataService Storage
) {
Contract.Requires(MapStorage != null);
Contract.Requires(Location != null);
Contract.Requires(Storage != null);
this.MapStorage = MapStorage;
this.Location = Location;
this.Storage = Storage;
ImageScale = 1.0;
ImageOffset = new Point();
SelectMap = new ReactiveCommand();
SelectMap
.Select(_ => Page.MapManagement)
.ToMessage(Messenger);
this.FirstActivation()
.Select(_ => Page.MapManagement)
.ToMessage(Messenger);
_CurrentMap = this.ObservableToProperty(Messenger.Listen<IElementVM<Map>>(MessageContracts.VIEW), x => x.CurrentMap);
_CurrentMap
.Where(vm => vm != null)
.Select(vm => Observable.Start(() => MapStorage.loadMap(vm.Model)))
.Switch()
.ObserveOnDispatcher()
.Select(stream => {
var img = new BitmapImage();
img.SetSource(stream);
stream.Close();
return img;
})
.Subscribe(x => MapImage = x);
var current_series = Messenger.Listen<ILocationOwner>(MessageContracts.VIEW);
var current_localizable = Messenger.Listen<ILocalizable>(MessageContracts.VIEW);
var current_series_if_not_localizable = current_series.Merge(current_localizable.Select(_ => null as ILocationOwner));
var current_localizable_if_not_series = current_localizable.Merge(current_series.Select(_ => null as ILocalizable));
var series_and_map =
current_series_if_not_localizable
.CombineLatest(_CurrentMap.Where(x => x != null), (es, map) =>
new { Map = map.Model, Series = es })
.Publish();
var add_locs =
series_and_map
.Select(pair => {
if (pair.Series != null) {
var stream = Storage.getGeoPointsForSeries(pair.Series.EntityID).ToObservable(ThreadPoolScheduler.Instance) //Fetch geopoints asynchronously on Threadpool thread
.Merge(Messenger.Listen<GeoPointForSeries>(MessageContracts.SAVE).Where(gp => gp.SeriesID == pair.Series.EntityID)) //Listen to new Geopoints that are added to the current tour
.Select(gp => pair.Map.PercentilePositionOnMap(gp))
.TakeUntil(series_and_map)
.Replay();
stream.Connect();
return stream as IObservable<Point?>;
}
else
return Observable.Empty<Point?>();
}).Replay(1);
_AdditionalLocalizations = add_locs;
add_locs.Connect();
series_and_map.Connect();
Observable.CombineLatest(
current_localizable_if_not_series,
_CurrentMap,
(loc, map) => {
if (map == null)
return null;
return map.Model.PercentilePositionOnMap(loc);
})
.Subscribe(c => PrimaryLocalization = c);
ToggleEditable = new ReactiveCommand(current_localizable_if_not_series.Select(l => l != null));
_IsEditable = this.ObservableToProperty(
current_localizable_if_not_series.Select(_ => false)
.Merge(ToggleEditable.Select(_ => true)),
x => x.IsEditable);
SetLocation = new ReactiveCommand(_IsEditable);
SetLocation
.Select(loc => loc as Point?)
.Where(loc => loc != null)
.Subscribe(loc => PrimaryLocalization = loc);
//.........这里部分代码省略.........
示例10: HomeVM
public HomeVM(
IFieldDataService Storage,
ILocationService Location,
[Dispatcher] IScheduler Dispatcher
)
{
this.Storage = Storage;
this.Location = Location;
//EventSeries
SeriesList = new ReactiveCollection<EventSeriesVM>();
getSeries.RegisterAsyncFunction(_ =>
Enumerable.Repeat(NoEventSeriesMixin.NoEventSeries, 1)
.Concat(
Storage
.getAllEventSeries()
)
.Select(es => new EventSeriesVM(es))
)
.SelectMany(vm => vm)
.ObserveOn(Dispatcher)
.Subscribe(SeriesList.Add);
SeriesList
.ListenToChanges<EventSeries, EventSeriesVM>();
(SelectSeries = new ReactiveCommand<IElementVM<EventSeries>>())
.ToMessage(Messenger, MessageContracts.VIEW);
(EditSeries = new ReactiveCommand<IElementVM<EventSeries>>(vm => vm.Model != NoEventSeriesMixin.NoEventSeries))
.ToMessage(Messenger, MessageContracts.EDIT);
var openSeries = SeriesList.CollectionCountChanged.Select(_ => Unit.Default)
.Merge(Messenger.Listen<IElementVM<EventSeries>>(MessageContracts.SAVE).Select(_ => Unit.Default))
.Select(_ => SeriesList.Where(s => s.Model.SeriesEnd == null))
.Select(list => list.FirstOrDefault());
openSeries
.SelectMany(series => (series != null) ?
Location.LocationByDistanceThreshold(20)
.Select(c =>
{
var gp = new Localization() { RelatedID = series.Model.SeriesID };
gp.SetCoordinates(c);
return gp;
})
.TakeUntil(openSeries) : Observable.Empty<Localization>())
.ObserveOn(Dispatcher)
.ToMessage(Messenger, MessageContracts.SAVE);
var noOpenSeries =
openSeries
.Select(openseries => openseries == null);
Settings = new ReactiveCommand();
Settings.Select(_ => Page.Settings)
.ToMessage(Messenger);
Add = new ReactiveCommand(noOpenSeries);
Add.Select(_ => new EventSeriesVM(new EventSeries()) as IElementVM<EventSeries>)
.ToMessage(Messenger, MessageContracts.EDIT);
Maps = new ReactiveCommand();
Maps.Select(_ => null as ILocalizable)
.ToMessage(Messenger, MessageContracts.VIEW);
Help = new ReactiveCommand();
Help.Select(_ => Page.Info)
.ToMessage(Messenger);
Messenger.Listen<EventMessage>(MessageContracts.INIT)
.Do(_ => SeriesList.Clear())
.Subscribe(_ => getSeries.Execute(null));
}
示例11: AddPackageViewModel
public AddPackageViewModel(
Func<string ,IObservable<string>> searchForPackages,
Action<NugetResult> addPackageCallback,
IObservable<Logging.Trace> paketTraceFunObservable)
{
var logger = new DebugLogger() {Level = LogLevel.Debug};
Splat.Locator.CurrentMutable.RegisterConstant(logger, typeof(ILogger));
_paketTraceFunObservable = paketTraceFunObservable;
SearchNuget =
ReactiveCommand.CreateAsyncObservable(
this.ObservableForProperty(x => x.SearchText)
.Select(x => !string.IsNullOrEmpty(SearchText)),
_ =>
searchForPackages(SearchText)
.Select(x => new NugetResult {PackageName = x}));
//TODO: Localization
var errorMessage = "NuGet packages couldn't be loaded.";
var errorResolution = "You may not have internet or NuGet may be down.";
SearchNuget.ThrownExceptions
.Log(this, "Search NuGet exception:", e => e.ToString())
.Select(ex => new UserError(errorMessage, errorResolution))
.SelectMany(UserError.Throw)
.Subscribe();
SearchNuget.IsExecuting
.Where(isExecuting => isExecuting)
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(_ =>
{
NugetResults.Clear();
});
SearchNuget.Subscribe(NugetResults.Add);
AddPackage = ReactiveCommand.CreateAsyncTask(
this.WhenAnyValue(x => x.SelectedPackage).Select(x => x != null),
_ => Task.Run(() => addPackageCallback(SelectedPackage)));
_addPackageState = AddPackage
.ThrownExceptions
.Log(this, "Add Package exception:", e => e.ToString())
.Select(_ => LoadingState.Failure)
.Merge(
AddPackage
.IsExecuting
.Where(isExecuting => isExecuting)
.Select(_ => LoadingState.Loading))
.Merge(
AddPackage
.Select(_ => LoadingState.Success))
.ToProperty(this, v => v.AddPackageState, out _addPackageState);
_addPackageState
.ThrownExceptions
.Log(this, "Add package state exception:", e => e.ToString())
.Select(ex => new UserError("", errorResolution))
.SelectMany(UserError.Throw)
.Subscribe();
this.ObservableForProperty(x => x.SearchText)
.Where(x => !string.IsNullOrEmpty(SearchText))
.Throttle(TimeSpan.FromMilliseconds(250))
.InvokeCommand(SearchNuget);
}
示例12: SettingsVM
public SettingsVM(
ISettingsService Settings,
ICleanupData Cleanup,
IConnectivityService Connectivity
) {
this.Cleanup = Cleanup;
this.Settings = Settings;
this.Connectivity = Connectivity;
this.WhenAny(x => x.Model, x => x.Value)
.Where(x => x != null)
.Select(m => m.UseGPS)
.Subscribe(x => UseGPS = x);
Reset = new ReactiveAsyncCommand(Connectivity.WifiAvailable());
Reset.RegisterAsyncTask(OnReset);
var setting_changed =
this.WhenAny(x => x.UseGPS, x => x.Model,
(gps, model) => (model.Value != null) ? model.Value.UseGPS != gps.Value : false);
Save = new ReactiveCommand(setting_changed);
Messenger.RegisterMessageSource(
Save
.Do(_ => saveModel())
.Select(_ => Page.Previous)
);
RefreshVocabulary = new ReactiveCommand(Connectivity.WifiAvailable());
RefreshVocabulary
.Subscribe(_ => {
Messenger.SendMessage(Page.SetupVocabulary);
});
ManageTaxa = new ReactiveCommand();
Messenger.RegisterMessageSource(
ManageTaxa
.Select(_ => Page.TaxonManagement)
);
UploadData = new ReactiveCommand();
Messenger.RegisterMessageSource(
UploadData
.Select(_ => Page.Upload)
);
DownloadData = new ReactiveCommand();
Messenger.RegisterMessageSource(
DownloadData
.Select(_ => Page.Download)
);
Info = new ReactiveCommand();
Messenger.RegisterMessageSource(
Info
.Select(_ => Page.Info)
);
ImportExport = new ReactiveCommand();
Messenger.RegisterMessageSource(
ImportExport
.Select(_ => Page.ImportExport)
);
Settings
.SettingsObservable()
.Subscribe(x => Model = x);
}
示例13: MainCalculatorViewModel
public MainCalculatorViewModel(IScreen host = null) : base(host) {
this.UrlPathSegment = "Loan Calculator";
Observable.Empty<double>().ToProperty(this, x => x.TotalPayment, out _totalPayment);
Observable.Empty<double>().ToProperty(this, x => x.TotalInterest, out _totalInterest);
ListPayments = new ReactiveList<dynamic>() {ChangeTrackingEnabled = true};
CalculateCommand = ReactiveCommand.CreateAsyncTask( async o => {
return await Task.Run(() => {
var A = LoanAmount*(1 + ((Interest/100)*LoanTermInYears));
dynamic data = new ExpandoObject();
data.TotalInterest = A - LoanAmount;
data.TotalPayment = A;
data.MonthlyPayment = A/LoanTermInMonths;
return data;
});
});
CalculateCommand.Subscribe();
var cal = CalculateCommand.Select(x => x);
cal.Select(x => (double)x.TotalPayment).ToProperty(this, x => x.TotalPayment, out _totalPayment);
cal.Select(x => (double)x.TotalInterest).ToProperty(this, x => x.TotalInterest, out _totalInterest);
cal.Subscribe(x => {
var principlePermonth = this.LoanAmount/this.LoanTermInMonths;
var interestPermonths = x.TotalInterest/this.LoanTermInMonths;
this.ListPayments.Clear();
for (int i = 0; i < this.LoanTermInMonths; i++) {
dynamic items =
new {
Date = this.StartTime.AddMonths(i).ToString("Y"),
Payment = x.MonthlyPayment.ToString("N2"),
Principle = principlePermonth.ToString("N2"),
Interest = interestPermonths.ToString("N2"),
TotalInterest = (interestPermonths * (i+1)).ToString("N2"),
Balance = (x.MonthlyPayment * (i+1)).ToString("N2")
};
ListPayments.Add(items);
}
});
this.WhenAnyValue(x => x.LoanTermInYears).Select(x => Convert.ToInt32(x*12)).BindTo(this, x => x.LoanTermInMonths);
Observable.Merge(
this.WhenAnyValue(x => x.LoanAmount).Select(x => Unit.Default),
this.WhenAnyValue(x => x.LoanTermInYears).Select(x => Unit.Default),
this.WhenAnyValue(x => x.LoanTermInMonths).Select(x => Unit.Default),
this.WhenAnyValue(x => x.StartTime).Select(x => Unit.Default),
this.WhenAnyValue(x => x.Interest).Select(x => Unit.Default)
).InvokeCommand(CalculateCommand);
}
示例14: MapManagementVM
public MapManagementVM(
IConnectivityService Network,
IMapTransferService MapService,
IMapStorageService MapStorage,
INotificationService Notifications,
[Dispatcher] IScheduler Dispatcher
) {
Contract.Requires(Network != null);
Contract.Requires(MapService != null);
Contract.Requires(MapStorage != null);
Contract.Requires(Notifications != null);
this.Network = Network;
this.MapService = MapService;
this.MapStorage = MapStorage;
this.FirstActivation()
.Subscribe(_ => getMaps.Execute(null));
MapList = getMaps.RegisterAsyncFunction(_ => MapStorage.getAllMaps().Select(m => new MapVM(m)))
.SelectMany(vms => vms.ToList())
.ObserveOn(Dispatcher)
.CreateCollection();
MapList.ItemsAdded
.Subscribe(item => _local_map_register.Add(item.ServerKey, Unit.Default));
MapList.ItemsRemoved
.Subscribe(item => _local_map_register.Remove(item.ServerKey));
SelectMap = new ReactiveCommand<MapVM>(vm => !vm.IsDownloading);
SelectMap
.Select(vm => vm as IElementVM<Map>)
.ToMessage(Messenger, MessageContracts.VIEW);
SelectMap
.Select(_ => Page.Previous)
.ToMessage(Messenger);
DeleteMap = new ReactiveCommand<MapVM>(vm => !vm.IsDownloading);
DeleteMap
.Do(vm => MapList.Remove(vm))
.Select(vm => vm.Model)
.Where(map => map != null)
.Subscribe(map => MapStorage.deleteMap(map));
_IsOnlineAvailable = this.ObservableToProperty(
this.OnActivation()
.SelectMany(Network.WifiAvailable().TakeUntil(this.OnDeactivation()))
.Do(x => { })
, x => x.IsOnlineAvailable, false);
SearchMaps = new ReactiveAsyncCommand(_IsOnlineAvailable);
_SearchResults = this.ObservableToProperty<MapManagementVM, IReactiveCollection<MapVM>>(
SearchMaps.RegisterAsyncFunction(s => searchMapsImpl(s as string))
.ObserveOn(Dispatcher)
.Select(result => {
try {
return new ReactiveCollection<MapVM>(result.Select(x => new MapVM(null) { ServerKey = x })) as IReactiveCollection<MapVM>;
}
catch (Exception) {
return null;
}
}),
x => x.SearchResults);
DownloadMap = new ReactiveCommand<MapVM>(vm => canBeDownloaded(vm as MapVM), Observable.Empty<Unit>());
DownloadMap
.Where(downloadMap.CanExecute)
.CheckConnectivity(Network, Notifications)
.Do(vm => vm.IsDownloading = true)
.Do(_ => CurrentPivot = Pivot.Local)
.Do(vm => MapList.Add(vm))
.Subscribe(downloadMap.Execute);
downloadMap.RegisterAsyncObservable(vm => {
var vm_t = vm as MapVM;
if (vm_t == null)
return Observable.Empty<System.Tuple<MapVM, Map>>();
else
return MapService.downloadMap(vm_t.ServerKey)
.ShowServiceErrorNotifications(Notifications)
.Catch((WebException ex) => {
Notifications.showNotification(DiversityResources.MapManagement_Message_NoPermissions);
return Observable.Empty<Map>();
})
.Select(map => System.Tuple.Create(vm_t, map));
})
.ObserveOn(Dispatcher)
.Select(t => {
if (t.Item1 != null) // VM
{
if (t.Item2 != null) // Map
{
t.Item1.SetModel(t.Item2);
}
else {
MapList.Remove(t.Item1);
//.........这里部分代码省略.........
示例15: CreateTicketsViewModel
public CreateTicketsViewModel(ISession session, IScreen screen = null)
{
#region Initialization
HostScreen = screen ?? new DefaultScreen(RxApp.DependencyResolver);
GoBack = HostScreen.Router.NavigateBack;
CurrentBatch = new ReactiveList<TicketItemViewModel>();
Customers = new ReactiveList<Customer>();
#endregion
#region Populate Customer List
session.FetchResults<Customer>()
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(c => Customers.Add(c));
#endregion
#region Wire Up Commands
AddTicket = new ReactiveCommand(
this.WhenAny(
x => x.CurrentBatch,
y => y.Problem,
z => z.SelectedCustomer,
(x, y, z) => x.Value.Count() <= 100 &&
!string.IsNullOrWhiteSpace(y.Value) &&
z.Value != null));
AddTicket.Subscribe(_ =>
{
CurrentBatch.Add(new TicketItemViewModel(Problem, CurrentBatch.Remove));
Problem = default(string);
});
var anyInList = CurrentBatch.Changed.Select(_ => CurrentBatch.Any());
var isCustomerSelected = this.WhenAnyValue(x => x.SelectedCustomer).Select(x => x != null);
var shouldSaveChanges = Observable.CombineLatest(anyInList, isCustomerSelected, (x, y) => x && y);
SaveChanges = new ReactiveCommand(shouldSaveChanges.StartWith(false));
_isExecuting = session.IsWorking.ToProperty(this, x => x.IsExecuting, false);
SaveChanges.Select(x => CurrentBatch.ToList())
.Subscribe(x =>
{
using (INotifyWhenComplete token = session.ScopedChanges())
{
var ticketTaker = session.Take<Ticket>();
token.Completion
.ObserveOn(RxApp.MainThreadScheduler)
.Subscribe(b => { if (b) (CurrentBatch as IList).Clear(); });
foreach (var item in x)
{
ticketTaker.Add(new Ticket
{
Description = item.Description,
CustomerId = SelectedCustomer.Id
});
}
}
});
#endregion
}