Xamarin.Forms:如何将NavigationPage XAML类添加到另一个XAML类?

3
以下代码可以正常工作:
<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.MainTabbedPage">
  <NavigationPage Title="asdfee">
    <x:Arguments>
      <ContentPage Title="asdf">
        <Label Text="asdfawwer"/>
      </ContentPage>
    </x:Arguments>
  </NavigationPage>
</TabbedPage>

但如果我想在不同目录中使用单独的XAML文件来创建NavigationPage,就会出现问题。例如:

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.MainTabbedPage"
             xmlns:layouts="clr-namespace:MyApp.Layouts">

  <layouts:MyNavigationPage Title="asdfee"/>

</TabbedPage>

在Layouts目录中有一个MyNavigationPage.xaml,但与先前的代码完全相同
<?xml version="1.0" encoding="utf-8" ?>
<NavigationPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.Layouts.MyNavigationPage">
  <x:Arguments>
    <ContentPage Title="asdf">
      <Label Text="asdfawwer"/>
    </ContentPage>
  </x:Arguments>
</NavigationPage>

当我这样做时,会抛出以下错误:
System.InvalidOperationException: NavigationPage 必须在使用之前具有根 Page。请先使用有效的 Page 调用 PushAsync,或将 Page 传递给构造函数。
当所有代码像第一个示例中一样,并且在 NavigationPage 的子项之前没有 时,我以前也遇到了同样的错误。所以我猜测这是与子项创建顺序有关的问题。
另外,如果我使用 ContentPage 的第二种方法,它就可以工作。
我是做错了什么还是应该填写错误报告?
有什么想法吗?
谢谢。
3个回答

3

通过添加 < TabbedPage.Children > 调整您的选项卡页面
像这样:(请注意,我添加了一个 CurrentPageChanged 事件)

<?xml version="1.0" encoding="utf-8" ?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        x:Class="MyApp.MainTabbedPage"
        xmlns:layouts="clr-namespace:MyApp.Layouts"
        CurrentPageChanged="TabbedPage_CurrentPageChanged"            
        >

<TabbedPage.Children>
    <NavigationPage Title="asdfee">
        <x:Arguments>
            <layouts:MyNavigationPage Icon="myIcon"/>
        </x:Arguments>
    </NavigationPage>
</TabbedPage.Children>

您要导航到的页面应该是ContentPage。在页面上添加标题。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="MyApp.Layouts.MyNavigationPage"
         Title="asdf">

    <Label Text="asdfawwer"/>

</ContentPage>

2

这是一个有趣的解决方案,不是吗? - rc1021
1
链接已失效。这个还有其他地方可以找到吗? - Le Mot Juiced

-1

我不相信你可以在XAML中创建NavigationPage。我总是通过代码来实现:

var nav = new NavigationPage(new MyContentXaml());

我不喜欢这种修复方法。要么我所有的东西都用C#,要么我的布局全部使用XAML。而且在XAML中它可以工作。虽然在这种情况下它表现出了奇怪的行为。 - Dpedrinha

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接