Version
Xamarin.Android 8.2
Xamarin.Forms 2.5
Short question
How do I, or should I let a ContentView know the life cycle state of its containing Page (e.g. Appearing, Disappearing, Sleeping)
Long question
I am learning how to create a reusable Xamarin ContentView. I decide to create a control <LabelCarousel/> that will display its children label one after another.
The problem is I have no idea how to stop the background timer that switches the content
Sample
Usage
<local:LabelCarousel>
<Label>Hello</Label>
<Label>Hola</Label>
</local:LabelCarousel>
Implementation
namespace XamarinStart.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
[ContentProperty("LabelContainer")]
public partial class LabelCarousel : ContentView
{
[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
[Description("Labels"), Category("Data")]
public List<Element> LabelContainer { get; } = new List<Element>();
private int _index = 0;
private Timer _timer = new Timer(2000);
public LabelCarousel ()
{
InitializeComponent ();
_timer.Elapsed += TimerEvent;
_timer.Start();
}
private void TimerEvent(object sender, ElapsedEventArgs e)
{
if (_index >= LabelContainer.Count)
{
_index = 0;
}
var selected = LabelContainer[_index++];
ChangeLabel((Label)selected);
}
private void ChangeLabel(Label lbl)
{
Device.BeginInvokeOnMainThread(async () =>
{
await this.FadeTo(0);
Content = lbl;
await this.FadeTo(1);
});
}
}
}
Problem
When I put this app into background, or push another activity on the top of this one, the timer is still running, wasting the CPU resource. Is there any good idea to let the reusable ContentView notified when the parent page changes the state?
Related Posts
https://forums.xamarin.com/discussion/38989/contentview-lifecycle https://forums.xamarin.com/discussion/65140/we-need-a-way-for-contentview-and-viewcells-to-monitor-their-own-lifecycle
Thank you!
