Created
May 4, 2020 20:30
-
-
Save dylanberry/320cd65d0f52f4a8ee56cac8ad1e8a76 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BaseTabViewModel : BaseViewModel, IActiveAware | |
{ | |
// NOTE: Prism.Forms only sets IsActive, and does not do anything with the event. | |
public BaseTabViewModel(INavigationService navigationService, | |
IViewModelServiceProvider viewModelServiceProvider) | |
: base(navigationService, viewModelServiceProvider) | |
{ | |
var onIsActiveChanged = new WeakEventHandler<EventArgs>(OnIsActiveChanged); | |
IsActiveChanged += onIsActiveChanged.Handler; | |
var onTabActivated = new WeakEventHandler<EventArgs>((sender, args) => | |
{ | |
if (!IsActive) return; | |
OnTabActivated().FireAndForgetSafeAsync(OnError); | |
}); | |
IsActiveChanged += onTabActivated.Handler; | |
} | |
public event EventHandler IsActiveChanged; | |
private bool _isActive; | |
public bool IsActive | |
{ | |
get => _isActive; | |
set => SetProperty(ref _isActive, value, RaiseIsActiveChanged); | |
} | |
protected virtual void RaiseIsActiveChanged() | |
{ | |
ViewModelServiceProvider.AnalyticsService.Screen(_navigationService.GetNavigationUriPath()); | |
IsActiveChanged?.Invoke(this, EventArgs.Empty); | |
} | |
protected virtual void OnIsActiveChanged(object sender, EventArgs e) | |
{ | |
} | |
protected virtual Task OnTabActivated() | |
{ | |
return Task.CompletedTask; | |
} | |
public override void OnNavigatedTo(INavigationParameters parameters) | |
{ | |
// Deep link navigation | |
if (parameters.TryGetValue(KnownNavigationParameters.SubPagePath, out string subPageNavigationUrl)) | |
NavigateAsync(subPageNavigationUrl, parameters).FireAndForgetSafeAsync(OnError); | |
else | |
base.OnNavigatedTo(parameters); | |
} | |
} | |
public sealed class WeakEventHandler<TEventArgs> where TEventArgs : System.EventArgs | |
{ | |
private readonly WeakReference _targetReference; | |
private readonly MethodInfo _method; | |
public WeakEventHandler(EventHandler<TEventArgs> callback) | |
{ | |
_method = callback.GetMethodInfo(); | |
_targetReference = new WeakReference(callback.Target, true); | |
} | |
public void Handler(object sender, TEventArgs e) | |
{ | |
var target = _targetReference.Target; | |
if (target == null) return; | |
var callback = (Action<object, TEventArgs>)_method.CreateDelegate(typeof(Action<object, TEventArgs>),target); | |
callback?.Invoke(sender, e); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment