Xamarin.Forms Menuitem

Download Sample 샘플 다운로드

클래스는 Xamarin.FormsMenuItem 항목 상황에 맞는 메뉴 및 셸 애플리케이션 플라이아웃 메뉴와 같은 ListView 메뉴에 대한 메뉴 항목을 정의합니다.

다음 스크린샷은 iOS 및 Android의 ListView 상황에 맞는 메뉴에 있는 개체를 보여줍니다MenuItem.

MenuItem 클래스는 다음 속성을 정의합니다.

  • CommandICommand viewmodel에 정의된 명령에 손가락 탭 또는 클릭과 같은 사용자 작업을 바인딩할 수 있도록 하는 것입니다.
  • CommandParameterobject 에 전달되어야 하는 매개 변수를 지정하는 입니다 Command.
  • IconImageSourceImageSource 표시 아이콘을 정의하는 값입니다.
  • IsDestructivebool 목록에서 연결된 UI 요소를 제거할지 여부를 MenuItem 나타내는 값입니다.
  • IsEnabledbool 는 이 개체가 사용자 입력에 응답하는지 여부를 나타내는 값입니다.
  • Textstring 표시 텍스트를 지정하는 값입니다.

이러한 속성은 개체에 의해 BindableProperty 지원되므로 인스턴스가 MenuItem 데이터 바인딩의 대상이 될 수 있습니다.

MenuItem 만들기

MenuItem 개체는 개체 항목의 상황에 맞는 메뉴 ListView 내에서 사용할 수 있습니다. 가장 일반적인 패턴은 인스턴스 내에서 개체를 만드는 MenuItem 것입니다. 이 개체는 인스턴스ItemTemplateDataTemplate 개체ListViewViewCell 사용됩니다. 개체가 채워지면 항목에 ListView 대해 상황에 맞는 메뉴가 활성화될 때 선택 항목을 노출하여 MenuItemDataTemplate항목을 만듭니다.

다음 예제에서는 개체의 ListView 컨텍스트 내에서 인스턴스화를 보여줍니다MenuItem.

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

코드에서 A MenuItem 를 만들 수도 있습니다.

// 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 동작 정의

MenuItem 클래스는 Clicked 이벤트를 노출합니다. 이벤트 처리기를 이 이벤트에 연결하여 XAML에서 인스턴스를 탭하거나 클릭하는 데 반응할 수 있습니다 MenuItem .

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

이벤트 처리기는 코드에 연결할 수도 있습니다.

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

이전 예제에서는 이벤트 처리기를 OnItemClicked 참조했습니다. 다음 코드는 예제 구현을 보여줍니다.

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 동작 정의

클래스는 MenuItem 개체 및 ICommand 인터페이스를 통해 BindableProperty MVVM(Model-View-ViewModel) 패턴을 지원합니다. 다음 XAML은 viewmodel에 정의된 명령에 바인딩된 인스턴스를 보여 MenuItem 줍니다.

<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 개체는 viewmodel의 명령에 바인딩된 속성과 CommandParameter 해당 Command 개체로 정의됩니다. viewmodel에는 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}";
    });
}

샘플 애플리케이션에는 개체를 채우기 위한 항목 목록을 가져오는 데 사용되는 클래스가 ListView 포함되어 DataService 있습니다. viewmodel은 클래스의 DataService 항목과 함께 인스턴스화되고 코드 숨김의 항목으로 BindingContext 설정됩니다.

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

Warning

MenuItem 개체는 Android에서 아이콘만 표시합니다. 다른 플랫폼에서는 속성에 지정된 Text 텍스트만 표시됩니다.

아이콘은 속성을 사용하여 IconImageSource 지정됩니다. 아이콘을 지정하면 속성에 지정된 텍스트가 Text 표시되지 않습니다. 다음 스크린샷은 Android의 MenuItem 아이콘을 보여줍니다.

에서 이미지를 Xamarin.Forms사용하는 방법에 대한 자세한 내용은 다음의 Xamarin.Forms이미지를 참조하세요.

런타임에 MenuItem 사용 또는 사용 안 함

런타임에 사용하지 않도록 설정 MenuItem 하려면 해당 Command 속성을 구현에 ICommand 바인딩하고 대리자가 해당 속성을 적절하게 사용하도록 설정하고 사용하지 않도록 설정해야 canExecute 합니다 ICommand .

Important

속성을 사용하거나 사용하지 않도록 설정하는 MenuItem경우 속성을 다른 속성에 Command 바인딩 IsEnabled 하지 마세요.

다음 예제에서는 속성이 MenuItemCommand 명명된 MyCommand속성에 바인딩되는 것을 ICommand 보여 줍니다.

<MenuItem Text="My menu item"
          Command="{Binding MyCommand}" />

구현을 ICommand 사용 하 고 canExecute 사용 하지 않도록 설정 하는 속성의 bool 값을 반환 하는 대리자가 MenuItem필요 합니다.

public class MyViewModel : INotifyPropertyChanged
{
    bool isMenuItemEnabled = false;
    public bool IsMenuItemEnabled
    {
        get { return isMenuItemEnabled; }
        set
        {
            isMenuItemEnabled = value;
            MyCommand.ChangeCanExecute();
        }
    }

    public Command MyCommand { get; private set; }

    public MyViewModel()
    {
        MyCommand = new Command(() =>
        {
            // Execute logic here
        },
        () => IsMenuItemEnabled);
    }
}

이 예제에서는 속성이 MenuItem 설정될 때까지 IsMenuItemEnabled 사용하지 않도록 설정됩니다. 이 경우 대리 MyCommand 자가 Command.ChangeCanExecute 다시 평가되도록 하는 canExecute 메서드가 호출됩니다.

플랫폼 간 상황에 맞는 메뉴 동작

상황에 맞는 메뉴에 액세스하고 각 플랫폼에서 다르게 표시됩니다.

Android에서 상황에 맞는 메뉴는 목록 항목을 길게 눌러 활성화됩니다. 상황에 맞는 메뉴는 제목 및 탐색 모음 영역을 대체하고 MenuItem 옵션은 가로 단추로 표시됩니다.

iOS에서 상황에 맞는 메뉴는 목록 항목을 살짝 밀어 활성화됩니다. 상황에 맞는 메뉴는 목록 항목에 표시되며 MenuItems 가로 단추로 표시됩니다.

UWP에서 상황에 맞는 메뉴는 목록 항목을 마우스 오른쪽 단추로 클릭하여 활성화됩니다. 상황에 맞는 메뉴는 커서 근처에 세로 목록으로 표시됩니다.