|
using System; |
|
using System.Runtime.CompilerServices; |
|
using Xamarin.Forms; |
|
|
|
namespace Smallgeek.Behaviors |
|
{ |
|
public class NotifyNavigationBehavior : BindableBehavior<Page> |
|
{ |
|
protected override void OnAttachedTo(Page bindable) |
|
{ |
|
base.OnAttachedTo(bindable); |
|
bindable.Appearing += OnAppearing; |
|
bindable.Disappearing += OnDisappearing; |
|
} |
|
|
|
protected override void OnDetachingFrom(Page bindable) |
|
{ |
|
bindable.Disappearing -= OnDisappearing; |
|
bindable.Appearing -= OnAppearing; |
|
base.OnDetachingFrom(bindable); |
|
} |
|
|
|
private void OnAppearing(object sender, EventArgs eventArgs) |
|
{ |
|
(AssociatedObject.BindingContext as IAppearingAware)?.OnAppearing(); |
|
|
|
var firstAppearing = AssociatedObject.BindingContext as IFirstAppearingAware; |
|
if (firstAppearing?.IsLoaded() == false) |
|
{ |
|
firstAppearing.OnFirstAppearing(); |
|
firstAppearing.MarkLoaded(); |
|
} |
|
} |
|
|
|
private void OnDisappearing(object sender, EventArgs eventArgs) |
|
{ |
|
(AssociatedObject.BindingContext as IDisappearingAware)?.OnDisappearing(); |
|
} |
|
} |
|
|
|
public static class FirstAppearingAwareExtension |
|
{ |
|
private readonly static ConditionalWeakTable<IFirstAppearingAware, Holder<bool>> holdPlaceState = new ConditionalWeakTable<IFirstAppearingAware, Holder<bool>>(); |
|
|
|
public static bool IsLoaded(this IFirstAppearingAware self) |
|
{ |
|
return holdPlaceState.GetOrCreateValue(self).Value; |
|
} |
|
|
|
public static void MarkLoaded(this IFirstAppearingAware self) |
|
{ |
|
holdPlaceState.GetOrCreateValue(self).Value = true; |
|
} |
|
} |
|
|
|
class Holder<T> where T : struct |
|
{ |
|
public T Value { get; set; } |
|
} |
|
} |