如何使用Xamarin.Forms创建滑块菜单?是烤制的还是定制的?
答案 0 :(得分:31)
您创建了一个新类,其中包含Master的所有定义 - 即菜单 - 和Detail - 即 main 页面。我知道,它听起来像是背靠背,但是例如..
using System;
using Xamarin.Forms;
namespace testXamForms
{
public class HomePage : MasterDetailPage
{
public HomePage()
{
// Set up the Master, i.e. the Menu
Label header = new Label
{
Text = "MENU",
Font = Font.BoldSystemFontOfSize(20),
HorizontalOptions = LayoutOptions.Center
};
// create an array of the Page names
string[] myPageNames = {
“Main”,
“Page 2”,
“Page 3”,
};
// Create ListView for the Master page.
ListView listView = new ListView
{
ItemsSource = myPageNames,
};
// The Master page is actually the Menu page for us
this.Master = new ContentPage
{
Title = "The Title is required.",
Content = new StackLayout
{
Children =
{
header,
listView
},
}
};
// Define a selected handler for the ListView contained in the Master (ie Menu) Page.
listView.ItemSelected += (sender, args) =>
{
// Set the BindingContext of the detail page.
this.Detail.BindingContext = args.SelectedItem;
Console.WriteLine("The args.SelectedItem is
{0}",args.SelectedItem);
// This is where you would put your “go to one of the selected pages”
// Show the detail page.
this.IsPresented = false;
};
// Set up the Detail, i.e the Home or Main page.
Label myHomeHeader = new Label
{
Text = "Home Page",
HorizontalOptions = LayoutOptions.Center
};
string[] homePageItems = { “Alpha”, “Beta”, “Gamma” };
ListView myHomeView = new ListView {
ItemsSource = homePageItems,
};
var myHomePage = new ContentPage();
myHomePage.Content = new StackLayout
{
Children =
{
myHomeHeader,
myHomeView
} ,
};
this.Detail = myHomePage;
}
}
}
答案 1 :(得分:16)
内置于:MasterDetailPage
。您可以将其Detail
和Master
属性设置为您喜欢的任何类型的页面。我发现Hansleman.Forms非常具有启发性。
答案 2 :(得分:13)
我的最小例子(发布here)如下:
public class App
{
static MasterDetailPage MDPage;
public static Page GetMainPage()
{
return MDPage = new MasterDetailPage {
Master = new ContentPage {
Title = "Master",
BackgroundColor = Color.Silver,
Icon = Device.OS == TargetPlatform.iOS ? "menu.png" : null,
Content = new StackLayout {
Padding = new Thickness(5, 50),
Children = { Link("A"), Link("B"), Link("C") }
},
},
Detail = new NavigationPage(new ContentPage {
Title = "A",
Content = new Label { Text = "A" }
}),
};
}
static Button Link(string name)
{
var button = new Button {
Text = name,
BackgroundColor = Color.FromRgb(0.9, 0.9, 0.9)
};
button.Clicked += delegate {
MDPage.Detail = new NavigationPage(new ContentPage {
Title = name,
Content = new Label { Text = name }
});
MDPage.IsPresented = false;
};
return button;
}
}
托管示例解决方案on GitHub。
在iOS上,结果如下所示(左:菜单打开,右:点击“B”后):
请注意,您需要将菜单图标添加为iOS项目中的资源。
答案 3 :(得分:5)
如果您正在寻找MasterDetailPage的简单示例,请在GitHub查看我的样本回购。非常好的例子也呈现here
答案 4 :(得分:2)