Xamarin Forms TabbedPage子页导航:点击按钮滑至指定子页面
问题描述
我在项目中实现TabbedPage导航,在Home页(第1个子页)设置了按钮,期望点击该按钮时平滑切换到MapsLocation页(第2个子页)。
我的TabbedPage XAML代码如下:
<TabbedPage android:TabbedPage.IsSmoothScrollEnabled="True" > <local:Home Title="Home"/> <local:MapsLocation Title="Map"/> <local:FeedbackPage Title="Feedback"/> <local:Profile Title="Profile"/> </TabbedPage>
按钮命令的代码如下:
public ICommand GotoCommand { get; } private async void GotoExecute(object sender) { var MyObject = (Shop)sender; await Navigation.PushAsync(new MapsLocation(MyObject.Address)); }
当前使用PushAsync会打开新页面,无法实现TabbedPage内的滑动切换至第2个子页,请问如何实现该需求?
解决方案
要实现TabbedPage内的页面切换,不能用PushAsync(这会在导航栈中新增独立页面),而是直接操作TabbedPage的选中项,同时利用已设置的平滑滚动属性,具体步骤如下:
获取父级TabbedPage实例
在Home页的按钮命令中,先定位当前页面所属的TabbedPage:var parentTabbedPage = this.Parent as TabbedPage;复用已有子页并传递参数
不能新建MapsLocation实例(否则会脱离TabbedPage的页面集合),需要找到TabbedPage中已存在的MapsLocation页,传递参数后切换选中状态:private void GotoExecute(object sender) { var MyObject = (Shop)sender; // 获取父级TabbedPage var parentTabbedPage = this.Parent as TabbedPage; if (parentTabbedPage == null) return; // 查找TabbedPage中已初始化的MapsLocation实例 var mapPage = parentTabbedPage.Children.OfType<MapsLocation>().FirstOrDefault(); if (mapPage != null) { // 给目标页面传递地址参数 mapPage.UpdateAddress(MyObject.Address); // 切换到该页面,已设置的IsSmoothScrollEnabled会自动触发平滑滚动 parentTabbedPage.CurrentPage = mapPage; } }在MapsLocation页添加参数接收方法
为了处理传递的地址参数,在MapsLocation类中新增如下方法:public void UpdateAddress(string address) { // 这里编写地址参数的处理逻辑,比如更新地图定位 // 示例:MyMapView.SetLocation(address); }关键注意点
- 禁止使用
PushAsync,否则会创建独立页面,破坏TabbedPage的导航结构 - XAML中已设置
android:TabbedPage.IsSmoothScrollEnabled="True",切换CurrentPage时会自动启用平滑滚动 - 确保TabbedPage的Children集合中已包含MapsLocation实例(即XAML中已声明),才能成功复用
- 禁止使用
内容的提问来源于stack exchange,提问作者Orijuela Dave
相关产品推荐
相关产品推荐

