这是我的代码.我想知道当用户点击已经选中的标签时我怎么能检测到我想要在play.png和pause.png之间切换aPage的图标加上我也想在APage上调用一个方法.
public partial class MainPage : TabbedPage { public MainPage() { InitializeComponent(); var aPage = new NavigationPage(new APage()) { Title = "Play",Icon = "play.png" }; var bPage = new NavigationPage(new BPage()) { Title = "Settings",Icon = "b.png" }; Children.Add(aPage); Children.Add(bPage); } }
请注意,如果可能,我想找到一个不涉及iOS和Android自定义渲染器的解决方案.我想知道我可以重新定义TabbedPage并将逻辑放在该类中吗?
解决方法
我知道您要避免使用自定义渲染器,但这只能通过使用自定义渲染器来实现.
码
Xamarin.Android自定义渲染器
using Android.Content; using Android.Support.Design.Widget; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Xamarin.Forms.Platform.Android.AppCompat; [assembly: ExportRenderer(typeof(MainPage),typeof(MainPageRenderer))] namespace YourNameSpace { public class MainPageRenderer : TabbedPageRenderer,TabLayout.IOnTabSelectedListener { MainPage _page; public MainPageRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<TabbedPage> e) { base.OnElementChanged(e); if (e.NewElement != null) _page = e.NewElement as MainPage; else _page = e.OldElement as MainPage; } void TabLayout.IOnTabSelectedListener.OnTabReselected(TabLayout.Tab tab) { System.Diagnostics.Debug.WriteLine("Tab Reselected"); //Handle Tab Reselected } } }
Xamarin.iOS自定义渲染器
using System; using System.Diagnostics; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(MainPage),typeof(MainPageRenderer))] namespace YourNameSpace { public class MainPageRenderer : TabbedRenderer { MainPage _page; protected override void OnElementChanged(VisualElementChangedEventArgs e) { base.OnElementChanged(e); if (e.NewElement != null) _page = e.NewElement as MainPage; else _page = e.OldElement as MainPage; try { if (ViewController is UITabBarController tabBarController) tabBarController.ViewControllerSelected += OnTabbarControllerItemSelected; } catch (Exception exception) { Debug.WriteLine(exception); } } void OnTabbarControllerItemSelected(object sender,UITabBarSelectionEventArgs eventArgs) { if (_page?.CurrentPage?.Navigation != null && _page.CurrentPage.Navigation.NavigationStack.Count > 0) { Debug.WriteLine("Tab Tapped"); //Handle Tab Tapped } } } }