如何从其他内容页面按钮单击打开主详细菜单?

时间:2018-03-16 10:24:54

标签: xamarin xamarin.forms

我想从另一个内容页面按钮点击事件打开主详细信息菜单? 那么如何用xamarin形式呢?

2 个答案:

答案 0 :(得分:3)

您可以通过将MasterDetailPage.IsPresented设置为true来打开菜单页。

执行此操作的简单方法是MessagingCenter。要MasterDetailPage添加MessagingCenter.Subscribe并在您的虚拟机中添加MessagingCenter.Send

实施例

public class MenuPage : ContentPage
{
    public MenuPage()
    {
        Title = "Test";
        Content = new StackLayout
        {
            Children = {
                new Label { Text = "Welcome to Xamarin.Forms!" }
            }
        };
    }
}

public class DetailPage : ContentPage
{
    public DetailPage()
    {
        var button = new Button()
        {
            Text = "Menu"
        };
        button.Clicked += Button_Clicked;
        Content = new StackLayout
        {
            Children = {
                button
            }
        };
    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        MessagingCenter.Send(EventArgs.Empty, "OpenMenu");
    }
}


public partial class App : Application
{
    public App()
    {
        InitializeComponent();

        var masterDetailPage = new MasterDetailPage();
        masterDetailPage.Master = new MenuPage();
        masterDetailPage.Detail = new NavigationPage( new DetailPage());
        MainPage = masterDetailPage;
        MessagingCenter.Subscribe<EventArgs>(this, "OpenMenu", args =>
        {
            masterDetailPage.IsPresented = true;
        });

    }
}

答案 1 :(得分:1)

在要打开“抽屉菜单”的页面上,必须在Click Event或任何所需的内容上设置“消息发送”。就我而言,我将其设置为点击图片的事件。

public void ToggleDrawer(object sender, System.EventArgs e)
{
  MessagingCenter.Send(EventArgs.Empty, "OpenMenu");
}

现在,在MasterDetailPage(在我的情况下为Mainpage.xaml.cs)上,您必须在该页面的InitializeComponent()上方放置一个消息订阅。

MessagingCenter.Subscribe<EventArgs>(this, "OpenMenu", args =>
{
   IsPresented = !IsPresented;
});

对我有用。