问题
In Xamarin Forms v4.0.0.394984 pre10 using Visual Studio 2017 I was able to add MenuItems to the Shell programatically in the constructor of the Shell using the MenuItemsCollection MenuItems.
Here is the code that works in v4.0.0.394984 pre10 (simplified it for this question to add a single hard-coded menuitem and function LoadView is not shown here)
public partial class Shell : Xamarin.Forms.Shell
{
public ICommand cmdLoadView { get; } = new Command(LoadView);
public Shell()
{
InitializeComponent();
BindingContext = this;
MenuItem mi = new MenuItem();
mi.Command = cmdLoadView;
mi.CommandParameter = "myCommand";
mi.Text = "sampleName";
MenuItems.Add(mi);
}
...
}
In all subsequent versions, this code does not work. Intellisense indicates that MenuItems is still part of the Shell, but I get a compilation error saying: error CS0103: The name 'MenuItems' does not exist in the current context.
When I reference as this.MenuItems I get the compilation error: error CS1061: 'Shell' does not contain a definition for 'MenuItems' and no accessible extension method 'MenuItems' accepting a first argument of type 'Shell' could be found (are you missing a using directive or an assembly reference?)
Is this possible in the current version of Xamarin.Forms? I've tried with each of the releases and pre-releases since v4 pre10 and none have worked.
Thanks is advance for any help!
回答1:
You need to add the MenuItem
objects to the Current.Items
property in your AppShell
implementation. Example:
// factory method to create MenuItem objects
private static MenuItem CreateMenuItem(string title, ICommand cmd)
{
var menuItem = new MenuItem();
menuItem.Text = title;
menuItem.Command = cmd;
return menuItem;
}
public AppShell()
{
...
// you can place this code in any method in the AppShell class
Current.Items.Add(CreateMenuItem("AppInfo", new Command(async () =>
{
ShellNavigationState state = Shell.Current.CurrentState;
await Shell.Current.Navigation.PushAsync(new AppInfoPage());
Shell.Current.FlyoutIsPresented = false;
})));
...
}
来源:https://stackoverflow.com/questions/56468775/in-xamarin-forms-shell-how-do-i-add-menuitems-programatically