显示菜单项
.NET Multi-platform App UI (.NET MAUI) MenuItem 类可用于定义菜单的菜单项,如 ListView 项上下文菜单和 Shell 应用浮出控件菜单。
以下屏幕截图显示了 Android 上 ListView 上下文菜单中的 MenuItem 对象:
MenuItem 类定义以下属性:
- Command,类型为 ICommand,允许将用户操作(如手指点击或单击)绑定到在 viewmodel 上定义的命令。
- CommandParameter,类型为
object
,指定应传递给Command
的参数。 - IconImageSource,类型为 ImageSource,定义菜单项图标。
- IsDestructive,类型为
bool
,表示 MenuItem 是否从列表中删除其关联的 UI 元素。 - IsEnabled,类型为
bool
,表示菜单项是否响应用户输入。 - Text,类型为
string
,指定菜单项文本。
这些属性由 BindableProperty 对象提供支持;也就是说,它们可以作为数据绑定的目标。
创建 MenuItem
要创建菜单项(例如,作为 ListView 对象的项的上下文菜单),请在用作 ListView ItemTemplate
的 DataTemplate 对象的 ViewCell 对象中创建 MenuItem 对象。 填充 ListView 对象时,它将使用 DataTemplate 创建每个项,并在激活项的上下文菜单时显示 MenuItem 选项。
以下示例显示如何在 ListView 对象的上下文中创建 MenuItem:
<ListView>
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:Monkey">
<ViewCell>
<ViewCell.ContextActions>
<MenuItem Text="Context menu option" />
</ViewCell.ContextActions>
<Label Text="{Binding Name}" />
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
此示例将生成一个包含文本的 MenuItem 对象。 但是,MenuItem 的外观因平台而异。
也可以在代码中创建 MenuItem:
// Return a ViewCell instance that is used as the template for each list item
DataTemplate dataTemplate = new DataTemplate(() =>
{
// A Label displays the list item text
Label label = new Label();
label.SetBinding(Label.TextProperty, static (Monkey monkey) => monkey.Name);
// A ViewCell serves as the DataTemplate
ViewCell viewCell = new ViewCell
{
View = label
};
// Add a MenuItem to the ContextActions
MenuItem menuItem = new MenuItem
{
Text = "Context menu option"
};
viewCell.ContextActions.Add(menuItem);
// Return the custom ViewCell to the DataTemplate constructor
return viewCell;
});
ListView listView = new ListView
{
...
ItemTemplate = dataTemplate
};
ListView 中的上下文菜单在每个平台上以不同的方式激活和显示。 在 Android 上,通过长按列表项来激活上下文菜单。 上下文菜单取代了标题栏和导航栏区域,且 MenuItem 选项显示为水平按钮。 在 iOS 上,上下文菜单通过在列表项上轻扫来激活。 上下文菜单显示在列表项上,且 MenuItems
显示为水平按钮。 在 Windows 上,右键单击列表项可激活上下文菜单。 上下文菜单以垂直列表的形式显示在光标附近。
定义 MenuItem 行为
MenuItem 类定义 Clicked 事件。 可以将事件处理程序附加到此事件,以响应对 MenuItem 对象的点击或单击:
<MenuItem ...
Clicked="OnItemClicked" />
也可以在代码中附加事件处理程序。
MenuItem item = new MenuItem { ... };
item.Clicked += OnItemClicked;
这些示例引用 OnItemClicked
事件处理程序,如以下示例所示:
void OnItemClicked(object sender, EventArgs e)
{
MenuItem menuItem = sender as MenuItem;
// Access the list item through the BindingContext
var contextItem = menuItem.BindingContext;
// Do something with the contextItem here
}
定义 MenuItem 外观
图标是使用 IconImageSource 属性指定的。 如果指定了图标,则不会显示由 Text 属性指定的文本。 下面的屏幕截图显示了 Android 上带有图标的 MenuItem:
MenuItem 对象在 Android 上仅显示图标。 在其他平台上,将只显示由 Text 属性指定的文本。
注意
图像可以存储在应用项目中的单个位置。 有关详细信息,请参阅将图像添加到 .NET MAUI 项目。
在运行时启用或禁用 MenuItem
若要在运行时启用或禁用 MenuItem,请将其 Command
属性绑定到 ICommand 实现,并确保 canExecute
委托根据需要启用和禁用 ICommand。
重要
使用 Command
属性以启用或禁用 MenuItem 时,不要将 IsEnabled
属性绑定到其他属性。