在Xamarin Forms v4.0.0.394984 pre10中,使用Visual Studio2017,我能够使用MenuItemsCollection MenuItems在外壳的构造函数中以编程方式将MenuItems添加到外壳中。
下面是在v4.0.0.394984 pre10中工作的代码(为了添加单个硬编码的菜单项,这里没有显示函数LoadView )
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);
}
...
}在所有后续版本中,此代码都不起作用。智能感知指示MenuItems仍然是外壳程序的一部分,但是我得到一个编译错误,说: error CS0103:名称'MenuItems‘在当前上下文中不存在。
当我作为外壳引用时,我得到了编译错误: error CS1061:‘this.MenuItems’不包含'MenuItems‘的定义,并且找不到接受’外壳‘类型的第一个参数的可访问扩展方法'MenuItems’(您是否缺少using指令或程序集引用?)
这在当前版本的Xamarin.Forms中是可能的吗?自从v4 pre10以来,我尝试了每一个版本和预发行版,但都没有成功。
感谢大家的帮助!
发布于 2019-08-19 22:24:43
您需要将MenuItem对象添加到AppShell实现中的Current.Items属性。示例:
// 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
复制相似问题