Created
January 2, 2020 02:24
-
-
Save dmariogatto/a9cd786f87243427494c46c57b7abd8c to your computer and use it in GitHub Desktop.
ContentView with Appearing & Disappearing events
This file contains hidden or 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
using System; | |
using System.Runtime.CompilerServices; | |
using Xamarin.Forms; | |
namespace YourAwesomeApp | |
{ | |
public class BaseView : ContentView | |
{ | |
private ContentPage _parentPage; | |
private bool _registered; | |
public BaseView() | |
{ | |
} | |
protected virtual void OnAppearing() | |
{ | |
} | |
protected virtual void OnDisappearing() | |
{ | |
} | |
protected override void OnPropertyChanged([CallerMemberName] string propertyName = null) | |
{ | |
base.OnPropertyChanged(propertyName); | |
if (propertyName.Equals("Renderer", StringComparison.OrdinalIgnoreCase)) | |
{ | |
// https://github.com/michaelstonis/xamarin.forms-renderer-property | |
var rr = DependencyService.Get<IRendererResolver>(); | |
if (rr.HasRenderer(this)) | |
{ | |
Unregister(); | |
var parent = Parent; | |
while (parent?.Parent != null && !(parent is ContentPage)) | |
{ | |
parent = parent.Parent; | |
} | |
if (parent is ContentPage page) | |
{ | |
_parentPage = page; | |
Register(); | |
} | |
} | |
else | |
{ | |
Unregister(); | |
} | |
} | |
} | |
private void Register() | |
{ | |
if (_parentPage != null && !_registered) | |
{ | |
_parentPage.Appearing += OnAppearing; | |
_parentPage.Disappearing += OnDisappearing; | |
_registered = true; | |
} | |
} | |
private void Unregister() | |
{ | |
if (_parentPage != null && _registered) | |
{ | |
_parentPage.Appearing -= OnAppearing; | |
_parentPage.Disappearing -= OnDisappearing; | |
_registered = false; | |
_parentPage = null; | |
} | |
} | |
private void OnAppearing(object sender, EventArgs e) | |
{ | |
OnAppearing(); | |
} | |
private void OnDisappearing(object sender, EventArgs e) | |
{ | |
OnDisappearing(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment