【发布时间】:2014-07-20 19:28:30
【问题描述】:
如何使用 Xamarin.Forms 创建滑块菜单?它是烘焙的还是定制的?
【问题讨论】:
标签: xamarin xamarin.forms
如何使用 Xamarin.Forms 创建滑块菜单?它是烘焙的还是定制的?
【问题讨论】:
标签: xamarin xamarin.forms
您创建一个新类,其中包含 Master(即 menu)和 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;
}
}
}
【讨论】:
它内置于:MasterDetailPage。您可以将它的Detail 和Master 属性设置为您想要的任何类型的页面。我发现Hansleman.Forms 很有启发性。
【讨论】:
我的最小示例(如 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 项目中。
【讨论】:
如果您正在寻找MasterDetailPage 的简单示例,请查看我在GitHub 的示例存储库。还提供了非常好的示例here
【讨论】: