Commands and gestures

Handle discrete actions and continuous touch gestures without replacing native control behavior.

Interactive controls use ICommand for actions that fit MVVM. CommunityToolkit commands can be assigned directly. Command.From creates a small command when the action belongs in the view:

new Button
{
    Text = "Retry",
    Command = viewModel.RetryCommand
};

new Label
{
    Text = "Reset",
    TapCommand = Command.From(() => Console.WriteLine("Grrr MVVM"))
};

The MVVM and binding guide covers how command-owning ViewModels attach to typed pages.

CanExecute controls whether a command-backed native control is enabled. Raise the command's normal CanExecuteChanged event when that state changes.

Shared view interaction

Every View supports:

  • TapCommand and an optional TapCommandParameter
  • DoubleTapCommand and an optional DoubleTapCommandParameter
  • LongPressCommand, an optional LongPressCommandParameter, and LongPressDuration
  • Pressed, which reports touch-down and release/cancellation
  • Panned, Pinched, and Rotated for continuous gestures

The continuous callbacks receive state and geometry. Apply values while the gesture is Changed, then settle the view when it ends:

card.Panned = gesture =>
{
    if (gesture.State is GestureState.Changed)
        card.Translation = gesture.Translation;

    if (gesture.State is GestureState.Ended or GestureState.Canceled)
    {
        View.Animate(
            Animation.Spring(),
            () => card.Translation = Point.Zero);
    }
};

Setting these callbacks installs native recognizers without preventing child controls from receiving their own touches. AddNativeGesture is the lifecycle-aware escape hatch when a UIKit gesture recognizer is needed directly; see native interop.

Use interactive animators when a pan or pinch should scrub an animation rather than applying its final state immediately.

Context menus

Add MenuAction entries to any view's ContextMenu:

card.ContextMenu.Add(new MenuAction
{
    Text = "Delete",
    Icon = ImageSource.Symbol("trash"),
    IsDestructive = true,
    Command = viewModel.DeleteCommand,
    CommandParameter = item
});

Collection item menus use the current item automatically when CommandParameter is null. Buttons also expose a menu; their control page covers the button-specific behavior.

Pointer and enabled state

IsEnabled disables touch interaction and updates the native enabled appearance where the control supports one. On iPad, PointerEffect selects the hover treatment shown for a trackpad or mouse. It defaults to None.

Use Focus() and Unfocus() for keyboard focus. Calling Focus() before a view has been realized is a no-op, so initial focus normally belongs in OnAppeared.