Xamarin表单主从页面菜单

时间:2019-02-28 20:02:27

标签: c# xamarin.forms master-detail

我有一个具有MasterDetailPage的MainPage,我正在使用它来存储菜单页面控件。菜单显示,但我无法导航到新页面。

  

我是否需要将MasterDetailPage.Detail添加到homePage.xaml?

Menu Color

MenuPage

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <StackLayout Orientation="Horizontal" Spacing="10">
        <Label VerticalOptions="Center" Text="SideDrawer" />
    </StackLayout>
    <StackLayout VerticalOptions="FillAndExpand">
        <ListView x:Name="ListViewMenu"
                HasUnevenRows="True">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid Padding="10">
                            <Label Text="{Binding Title}" FontSize="20"/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>
</Grid>
public partial class MenuPage : ContentPage
{
    MainPage RootPage { get => Application.Current.MainPage as MainPage; }
    public NavigationPage Detail { get; private set; }
    List<HomeMenuItem> menuItems;
    public MenuPage ()
    {
        InitializeComponent ();
        menuItems = new List<HomeMenuItem>
        {
            new HomeMenuItem {Id = MenuItemType.Home, Title="Home" ,IconSource="Home.png", TargetType = typeof(Pages.HomePage)},
            new HomeMenuItem {Id = MenuItemType.Share, Title="Share App" ,IconSource="Home.png" ,TargetType = typeof(Pages.HomePage)},
            new HomeMenuItem {Id = MenuItemType.About, Title="About App",IconSource="Home.png",TargetType = typeof(Pages.HomePage) }
        };
        ListViewMenu.ItemsSource = menuItems;
        ListViewMenu.ItemSelected += OnItemSelected;
    }
    void OnItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var item = e.SelectedItem as HomeMenuItem;
        if (item != null)
        {
            //This will create instance of the page using the parameterized constructor you defined in each DetailPages
            Detail = new NavigationPage((Page)Activator.CreateInstance(item.TargetType));
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您需要一个继承自MasterDetailPage的页面。这将为您提供一个 Detail 属性,以正确设置和导航。

我建议您按照本指南为您提供帮助!

Xamarin.Forms Master-Detail Page