wabbajack/Wabbajack.App.Wpf/View Models/BackNavigatingVM.cs

76 lines
2.3 KiB
C#
Raw Normal View History

2021-12-26 21:56:44 +00:00
using System;
using System.Reactive;
using System.Reactive.Disposables;
2021-12-26 21:56:44 +00:00
using System.Reactive.Linq;
using System.Reactive.Subjects;
2021-12-27 23:15:30 +00:00
using Microsoft.Extensions.Logging;
2021-12-26 21:56:44 +00:00
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Wabbajack.Common;
2021-12-30 00:15:37 +00:00
using Wabbajack;
using Wabbajack.Messages;
2021-12-26 21:56:44 +00:00
namespace Wabbajack
{
public interface IBackNavigatingVM : IReactiveObject
{
ViewModel NavigateBackTarget { get; set; }
ReactiveCommand<Unit, Unit> BackCommand { get; }
Subject<bool> IsBackEnabledSubject { get; }
IObservable<bool> IsBackEnabled { get; }
}
public class BackNavigatingVM : ViewModel, IBackNavigatingVM
{
[Reactive]
public ViewModel NavigateBackTarget { get; set; }
public ReactiveCommand<Unit, Unit> BackCommand { get; protected set; }
[Reactive]
public bool IsActive { get; set; }
2021-12-26 21:56:44 +00:00
public Subject<bool> IsBackEnabledSubject { get; } = new Subject<bool>();
public IObservable<bool> IsBackEnabled { get; }
public BackNavigatingVM(ILogger logger)
2021-12-26 21:56:44 +00:00
{
IsBackEnabled = IsBackEnabledSubject.StartWith(true);
BackCommand = ReactiveCommand.Create(
2021-12-27 23:15:30 +00:00
execute: () => logger.CatchAndLog(() =>
2021-12-26 21:56:44 +00:00
{
NavigateBack.Send();
2021-12-26 21:56:44 +00:00
Unload();
}),
canExecute: this.ConstructCanNavigateBack()
.ObserveOnGuiThread());
this.WhenActivated(disposables =>
{
IsActive = true;
Disposable.Create(() => IsActive = false).DisposeWith(disposables);
});
2021-12-26 21:56:44 +00:00
}
public virtual void Unload()
{
}
}
public static class IBackNavigatingVMExt
{
public static IObservable<bool> ConstructCanNavigateBack(this IBackNavigatingVM vm)
{
return vm.WhenAny(x => x.NavigateBackTarget)
.CombineLatest(vm.IsBackEnabled)
.Select(x => x.First != null && x.Second);
}
2021-12-26 21:56:44 +00:00
public static IObservable<bool> ConstructIsActive(this IBackNavigatingVM vm, MainWindowVM mwvm)
{
return mwvm.WhenAny(x => x.ActivePane)
.Select(x => object.ReferenceEquals(vm, x));
}
}
}