Thursday, 4 October 2012

Windows 8 ItemTapCommand Attached Property

This attached property picks up touch tap events from FrameworkElements and triggers an attached command. This is useful for controls like GridViews where you might click an item or tap it to perform an action.


public class ItemTapCommand
{
  public static readonly DependencyProperty CommandProperty =
            DependencyProperty.RegisterAttached("Command", typeof(ICommand), typeof(ItemTapCommand), new PropertyMetadata(null, CommandPropertyChanged));

  public static void SetCommand(DependencyObject attached, ICommand value)
  {
    attached.SetValue(CommandProperty, value);
  }

  public static ICommand GetCommand(DependencyObject attached)
  {
    return (ICommand)attached.GetValue(CommandProperty);
  }

  private static void CommandPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    // Attach tap handler
    (d as FrameworkElement).Tapped += ItemTapCommand_Tapped;
  }
       
  private static void ItemTapCommand_Tapped(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
  {
    // Get command
    ICommand command = GetCommand(sender as DependencyObject);

    // Execute command
    command.Execute(null);
  }
}

This example shows it attached to a GridView item (grid) and using a command from the view model via the context of the GridView:

<GridView ItemsSource="{Binding Items}"
  SelectedItem="{Binding SelectedItem, Mode=TwoWay}" SelectionMode="Single">
  <GridView.ItemTemplate>
    <DataTemplate>
      <Grid Width="133" Height="200"
cmd:ItemTapCommand.Command="{Binding ElementName=posterGrid, Path=DataContext.EditCommand}">


No comments:

Post a Comment