事件 OnDisappearing 在我这边在 iOS 和 Android 上都可以正常工作。如果您的项目仍然存在问题。您可以使用以下解决方法。
在xml中
<CarouselPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:CarouselPageDemo"
x:Class="CarouselPageDemo.MyCarouselPage"
CurrentPageChanged="CarouselPage_CurrentPageChanged">
在 CarouselPage.xaml.cs 中
int CurrentIndex = 0;
//...
private void CarouselPage_CurrentPageChanged(object sender, EventArgs e)
{
var index = this.Children.IndexOf(this.CurrentPage);
var ind = CurrentIndex.ToString();
if (index != CurrentIndex)
{
MessagingCenter.Send<Object>(this, ind);
}
if (index > -1)
{
CurrentIndex = index;
}
}
在子页面中
public Page1()
{
InitializeComponent();
MessagingCenter.Subscribe<Object>(this, "0", (org) =>
{
// ... handle the logic when the page will disappearing
});
}
注意:此处的0在您的子页面中会有所不同(0,1,2,...)
更新
public partial class MainPage : CarouselPage
{
int LastIndex=0;
public MainPage()
{
InitializeComponent();
this.Children.Add(new Page1());
this.Children.Add(new Page2());
this.Children.Add(new Page3());
CurrentPage = Children[0];
MessagingCenter.Subscribe<App, string>((App)Xamarin.Forms.Application.Current, "child", (s, child) =>
{
CurrentPage = Children[Int32.Parse(child)];
});
}
private void CarouselPage_CurrentPageChanged(object sender, EventArgs e)
{
var index = this.Children.IndexOf(this.CurrentPage);
string title = this.CurrentPage.Title;
Debug.WriteLine("title:>>" + title);
if (!string.IsNullOrEmpty(title)&& LastIndex!=index)
{
MessagingCenter.Send<MainPage>(this, title);
}
if (index > -1)
{
LastIndex = index;
}
}
}
}