Skip to content

Instantly share code, notes, and snippets.

@smallgeek
Created July 13, 2017 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smallgeek/85c80be7022ba26624820068f4042b4b to your computer and use it in GitHub Desktop.
Save smallgeek/85c80be7022ba26624820068f4042b4b to your computer and use it in GitHub Desktop.
nuits さんのコード (http://www.nuits.jp/entry/2016/09/26/221142) をベースに、画面遷移された初回だけ処理を実行させる
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; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment