OnOptionsItemSelected()方法永远不会被调用,如果它是Masterdetail页面。如果是常规导航页面,则可以使用。
答案 0 :(得分:0)
看了Xamarin.Forms来源似乎我找到了解决方案。
您必须为NavigationPage
创建渲染器并覆盖OnAttachedToWindow
。
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
Element page = Element.Parent;
MasterDetailPage masterDetailPage = null;
while (page != null)
{
if (page is MasterDetailPage)
{
masterDetailPage = page as MasterDetailPage;
break;
}
page = page.Parent;
}
if (masterDetailPage == null)
{
return;
}
var renderer = Platform.GetRenderer(masterDetailPage) as MasterDetailPageRenderer;
if (renderer == null)
{
return;
}
var drawerLayout = (DrawerLayout) renderer;
Toolbar toolbar = null;
for (int i = 0; i < ChildCount; i++)
{
var child = GetChildAt(i);
toolbar = child as Toolbar;
if (toolbar != null)
{
break;
}
}
toolbar?.SetNavigationOnClickListener(new MenuClickListener(Element, drawerLayout));
}
private class MenuClickListener : Java.Lang.Object, IOnClickListener
{
readonly NavigationPage navigationPage;
private DrawerLayout layout;
public MenuClickListener(NavigationPage navigationPage, DrawerLayout layout)
{
this.navigationPage = navigationPage;
this.layout = layout;
}
public void OnClick(View v)
{
var page = navigationPage.CurrentPage as BasePage;
if (navigationPage.Navigation.NavigationStack.Count <= 1)
{
layout.OpenDrawer((int) GravityFlags.Left);
}
if (page != null)
{
if (page.OnNavigationBackButtonPressed())
{
navigationPage?.PopAsync();
}
}
else
{
navigationPage?.PopAsync();
}
}
}
BasePage
- 来自ContentPage
,并且方法OnNavigationBackButtonPressed
可以处理特殊逻辑。