Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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