需求介绍
先介绍一下需求,使用MAUI平台开发android应用,需要完成在页面A中点击按钮进入页面B,页面B中会展示列表数据,需要点击其中一项将Item数据传回给页面A,此时页面B关闭。同时也需要实现在页面B中可点击关闭和导航栏Back返回页面A。
MAUI推荐使用Shell进行页面导航,所以本次实现也选择官方推荐的方式:
.NET MAUI Shell 导航 - .NET MAUI | Microsoft Learn
具体实现
MainPage作为页面A,DeviceListPage作为页面B。MainPage在创建MAUI项目时就在AppShell.xaml中已经注册了,现在要注册DeviceListPage页面的路由。在AppShell.xaml.cs中注册:
public AppShell()
{
InitializeComponent();
Routing.RegisterRoute("MainPage/DeviceListPage", typeof(DeviceListPage));
}
将DeviceListPage的路由注册为MainPage/DeviceListPage,这样的意思是需要从MainPage导航到DeviceListPage,构建导航堆栈,由MainPage页面打开DeviceListPage页面,DeviceListPage页面压入栈中处于栈顶,这样才能实现在DeviceListPage页面通过“后退”按钮或导航栏Back才能返回MainPage页面,使MainPage页面重新返回栈顶。
MainPage页面导航到DeivcePage页面:
await Shell.Current.GoToAsync("//MainPage/DeviceListPage");
将数据传回MainPage页面
- 给CollectionView添加点击选择事件
CollectionList.ItemsSource = DeviceModels;
CollectionList.SelectionChanged += CollectionList_SelectionChanged;
- 实现CollectionView的点击选择事件 将数据包装成ShellNavigationQueryParameters类型的变量,Key为“Address”,在导航中作为参数传递给MainPage页面,导航这是使用".."表示回退,也就是根据导航堆栈回退到上一页面MainPage页面。
private async void CollectionList_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var address = (e.CurrentSelection.FirstOrDefault() as DeviceModel)?.Address;
if (!string.IsNullOrEmpty(address))
{
var deviceParameter = new ShellNavigationQueryParameters
{
{"Address",address}
};
await Shell.Current.GoToAsync("..", deviceParameter);
}
}
- 在MainPage页面接受和处理参数 首先先声明一个Address属性,属性类型为string,然后在MainPage上添加特性QueryProperty,nameof函数中的参数为我们声明的Address,“Address”为DeviceListPage页面传递过来的参数的Key名称。
private string _address;
public string Address
{
get { return _address; }
set
{
_address = value;
}
}
[QueryProperty(nameof(Address), "Address")]
public partial class MainPage : ContentPage
按钮返回上一页
上面给CollectionView添加点击选择事件中已经有所介绍了,这里再贴一下按钮事件代码以及官网介绍:
private async void Button_Clicked(object sender, EventArgs e)
{
await Shell.Current.GoToAsync("..");
}
OK,本篇文章就介绍这么多了,如果我有哪里介绍错了,欢迎各位指正~~~