earthling
earthling

Reputation: 5264

Binding CommandParameter on ItemsControl Tap event

I'm using an ItemsControl, and I want to identify which item was selected on the Tap command. My xaml is defined here:

<ItemsControl ItemsSource="{Binding AllMyItems}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Tap">
              <cmd:EventToCommand Command="{Binding ItemSelectedCommand}" CommandParameter="{Binding}"/>
         </i:EventTrigger>
    </i:Interaction.Triggers>
    .... item template ....

and here is my view model:

public RelayCommand<MyItem> ItemSelectedCommand { get; private set; }
public MainViewModel()
    {
        ItemSelectedCommand = new RelayCommand<MyItem>(ItemSelected);
    }

private void ItemSelected(MyItem myItem)
    {
        throw new NotImplementedException();
    }

The event to command works, but when I get to the ItemSelected method, myItem is either Null, or I get an exception casting it (depending on how I define the CommandParameter in the xaml).

I can do this if I use a ListBox and set CommandParameter="{Binding SelectedItem, ElementName=MyItemsList"}

Any ideas on how to do this with ItemsControl? Or does the perf difference not make much of a difference between the two in Mango?

Upvotes: 4

Views: 1947

Answers (1)

Musaab
Musaab

Reputation: 805

Your Tap Event is occuring on the ItemsControl , you should place your EventToCommand inside the ItemTemplate , some XAML to clear the things for you

<ItemsControl ItemsSource="{Binding AllMyItems}">
<ItemsControl.ItemTemplate>
<...>
<i:Interaction.Triggers>
    <i:EventTrigger EventName="Tap">
          <cmd:EventToCommand Command="{Binding ItemSelectedCommand}" CommandParameter="{Binding}"/>
     </i:EventTrigger>
</i:Interaction.Triggers>
</...>                                    
</ItemsControl.ItemTemplate>
...

Upvotes: 2

Related Questions