【发布时间】:2018-03-21 00:14:07
【问题描述】:
版本
Xamarin.Android 8.2
Xamarin.Forms 2.5
小问题
我如何,或者我应该让 ContentView 知道其包含页面的生命周期状态(例如,出现、消失、睡眠)
长问题
我正在学习如何创建可重用的 Xamarin ContentView。我决定创建一个控件<LabelCarousel/>,它将一个接一个地显示其子标签。
问题是我不知道如何停止切换内容的后台计时器
示例
用法
<local:LabelCarousel>
<Label>Hello</Label>
<Label>Hola</Label>
</local:LabelCarousel>
实施
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);
});
}
}
}
问题
当我将此应用程序置于后台,或在此应用程序顶部推送另一个活动时,计时器仍在运行,浪费 CPU 资源。有什么好主意让可重用的 ContentView 在父页面更改状态时得到通知?
相关帖子
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
谢谢!
【问题讨论】:
标签: c# xaml xamarin xamarin.forms