Xamarin。窗体 MenuItemXamarin.Forms MenuItem

下载示例 下载示例Download Sample Download the sample

Xamarin MenuItem类定义菜单的菜单项,如 ListView 项上下文菜单和 Shell 应用程序飞出菜单。The Xamarin.Forms MenuItem class defines menu items for menus such as ListView item context menus and Shell application flyout menus.

以下屏幕截图显示 iOS 和 Android 上 ListView 上下文菜单中的 MenuItem 对象:The following screenshots show MenuItem objects in a ListView context menu on iOS and Android:

"IOS 和 Android 上的菜单项""MenuItems on iOS and Android"

@No__t_0 类定义以下属性:The MenuItem class defines the following properties:

  • Command是一种允许将用户操作(如指指点击或单击)绑定到 viewmodel 上定义的命令的 ICommandCommand is an ICommand that allows binding user actions, such as finger taps or clicks, to commands defined on a viewmodel.
  • CommandParameter是指定应传递到 Command 的参数的 objectCommandParameter is an object that specifies the parameter that should be passed to the Command.
  • IconImageSource是定义显示图标的 ImageSource 值。IconImageSource is an ImageSource value that defines the display icon.
  • IsDestructive是一个 bool 值,该值指示 MenuItem 是否从列表中删除其关联的 UI 元素。IsDestructive is a bool value that indicates whether the MenuItem removes its associated UI element from the list.
  • IsEnabled是确定此对象是否响应用户输入的 bool 值。IsEnabled is a bool value that determines whether this object responds to user input.
  • Text是指定显示文本的 string 值。Text is a string value that specifies the display text.

这些属性由BindableProperty对象支持,因此 MenuItem 实例可以是数据绑定的目标。These properties are backed by BindableProperty objects so the MenuItem instance can be the target of data bindings.

创建 MenuItemCreate a MenuItem

MenuItem 对象可在 ListView 对象项的上下文菜单中使用。MenuItem objects can be used within a context menu on a ListView object's items. 最常见的模式是在 ViewCell 实例中创建 MenuItem 对象,该实例用作 ListViews ItemTemplateDataTemplate 对象。The most common pattern is to create MenuItem objects within a ViewCell instance, which is used as the DataTemplate object for the ListViews ItemTemplate. 填充 ListView 对象时,它会使用 DataTemplate 创建每个项,并在为项激活上下文菜单时公开 MenuItem 选项。When the ListView object is populated it will create each item using the DataTemplate, exposing the MenuItem choices when the context menu is activated for an item.

下面的示例演示 ListView 对象的上下文中 MenuItem 实例化:The following example shows MenuItem instantiation within the context of a ListView object:

<ListView>
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <ViewCell.ContextActions>
                    <MenuItem Text="Context Menu Option" />
                </ViewCell.ContextActions>
                <Label Text="{Binding .}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

还可以在代码中创建 MenuItemA MenuItem can also be created in code:

// A function returns 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, ".");

    // A ViewCell serves as the DataTemplate
    ViewCell viewCell = new ViewCell
    {
        View = label
    };

    // Add a MenuItem instance to the ContextActions
    MenuItem menuItem = new MenuItem
    {
        Text = "Context Menu Option"
    };
    viewCell.ContextActions.Add(menuItem);

    // The function returns the custom ViewCell
    // to the DataTemplate constructor
    return viewCell;
});

// Finally, the dataTemplate is provided to
// the ListView object
ListView listView = new ListView
{
    ...
    ItemTemplate = dataTemplate
};

定义包含事件的 MenuItem 行为Define MenuItem behavior with events

MenuItem 类会公开 Clicked 事件。The MenuItem class exposes a Clicked event. 可以将事件处理程序附加到此事件,以响应在 XAML 中单击或单击 MenuItem 实例:An event handler can be attached to this event to react to taps or clicks on the MenuItem instance in XAML:

<MenuItem ...
          Clicked="OnItemClicked" />

事件处理程序也可以在代码中附加:An event handler can also be attached in code:

MenuItem item = new MenuItem { ... }
item.Clicked += OnItemClicked;

前面的示例引用 OnItemClicked 事件处理程序。Previous examples referenced an OnItemClicked event handler. 下面的代码演示实现示例:The following code shows an example implementation:

void OnItemClicked(object sender, EventArgs e)
{
    // The sender is the menuItem
    MenuItem menuItem = sender as MenuItem;

    // Access the list item through the BindingContext
    var contextItem = menuItem.BindingContext;

    // Do something with the contextItem here
}

通过 MVVM 定义 MenuItem 行为Define MenuItem behavior with MVVM

@No__t_0 类通过BindableProperty对象和 ICommand 接口支持模型-视图-VIEWMODEL (MVVM)模式。The MenuItem class supports the Model-View-ViewModel (MVVM) pattern through BindableProperty objects and the ICommand interface. 以下 XAML 显示了绑定到 viewmodel 上定义的命令的 MenuItem 实例:The following XAML shows MenuItem instances bound to commands defined on a viewmodel:

<ContentPage.BindingContext>
    <viewmodels:ListPageViewModel />
</ContentPage.BindingContext>

<StackLayout>
    <Label Text="{Binding Message}" ... />
    <ListView ItemsSource="{Binding Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <ViewCell.ContextActions>
                        <MenuItem Text="Edit"
                                    IconImageSource="icon.png"
                                    Command="{Binding Source={x:Reference contentPage}, Path=BindingContext.EditCommand}"
                                    CommandParameter="{Binding .}"/>
                        <MenuItem Text="Delete"
                                    Command="{Binding Source={x:Reference contentPage}, Path=BindingContext.DeleteCommand}"
                                    CommandParameter="{Binding .}"/>
                    </ViewCell.ContextActions>
                    <Label Text="{Binding .}" />
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</StackLayout>

在前面的示例中,两个 MenuItem 对象均由其 Command 和绑定到 viewmodel 上命令的 CommandParameter 属性定义。In the previous example, two MenuItem objects are defined with their Command and CommandParameter properties bound to commands on the viewmodel. Viewmodel 包含 XAML 中引用的命令:The viewmodel contains the commands referenced in the XAML:

public class ListPageViewModel : INotifyPropertyChanged
{
    ...

    public ICommand EditCommand => new Command<string>((string item) =>
    {
        Message = $"Edit command was called on: {item}";
    });

    public ICommand DeleteCommand => new Command<string>((string item) =>
    {
        Message = $"Delete command was called on: {item}";
    });
}

示例应用程序包括一个 DataService 类,该类用于获取用于填充 ListView 对象的项的列表。The sample application includes a DataService class used to get a list of items for populating the ListView objects. 使用 DataService 类中的项来实例化 viewmodel,并将其设置为代码隐藏中的 BindingContextA viewmodel is instantiated, with items from the DataService class, and set as the BindingContext in the code-behind:

public MenuItemXamlMvvmPage()
{
    InitializeComponent();
    BindingContext = new ListPageViewModel(DataService.GetListItems());
}

警告

MenuItem 对象只显示 Android 上的图标。MenuItem objects only display icons on Android. 在其他平台上,只会显示 Text 属性指定的文本。On other platforms, only the text specified by the Text property will be displayed.

图标是使用 IconImageSource 属性指定的。Icons are specified using the IconImageSource property. 如果指定了图标,则不会显示 Text 属性指定的文本。If an icon is specified, the text specified by the Text property will not be displayed. 以下屏幕截图显示了 Android 上带有图标的 MenuItemThe following screenshot shows a MenuItem with an icon on Android:

"Android 上的 MenuItem 图标屏幕截图""Screenshot of MenuItem icon on Android"

有关在 Xamarin 中使用图像的详细信息,请参阅xamarin 中的图像For more information on using images in Xamarin.Forms, see Images in Xamarin.Forms.

跨平台上下文菜单行为Cross-platform context menu behavior

上下文菜单在每个平台上以不同的方式进行访问和显示。Context menus are accessed and displayed differently on each platform.

在 Android 上,通过长时间按列表项激活上下文菜单。On Android, the context menu is activated by long-press on a list item. 上下文菜单替换标题和导航栏区域,MenuItem 选项显示为水平按钮。The context menu replaces the title and navigation bar area and MenuItem options are displayed as horizontal buttons.

"Android 上上下文菜单的屏幕截图""Screenshot of context menu on Android"

在 iOS 上,通过在列表项上轻扫激活上下文菜单。On iOS, the context menu is activated by swiping on a list item. 上下文菜单将显示在列表项上,并且 MenuItems 将显示为水平按钮。The context menu is displayed on the list item and MenuItems are displayed as horizontal buttons.

"IOS 上上下文菜单的屏幕截图""Screenshot of context menu on iOS"

在 UWP 上,右键单击列表项即可激活上下文菜单。On UWP, the context menu is activated by right-clicking on a list item. 上下文菜单将作为垂直列表显示在光标附近。The context menu is displayed near the cursor as a vertical list.

"UWP 上的上下文菜单的屏幕截图""Screenshot of context menu on UWP"