I am using ContextMenu from Windows Phone Control toolkit. Wondering how do I know which list item in the list is pressed? It seems I can know which context menu is selected but I have no way to know which list item is operated on. Please help. Thanks!
<DataTemplate x:Key="ListItemTemplate">
<StackPanel Grid.Column="1" VerticalAlignment="Top">
<TextBlock Tag="{Binding Index}" Text="{Binding SName}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}" />
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="Add to playlist" Click="Move_Click"/>
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
</StackPanel>
private void Move_Click(object sender, RoutedEventArgs e)
{
String name = (string)((MenuItem)sender).Header;
// how to know which index of the item is targeted on
}
The answer is: MVVM. Don't use the event registration in code-behind rather have a command be invoked in the ViewModel. First, Instead of binding to a Data object, bind to a ViewModel (or a ViewModel representing a single list item if you're in a list). Then instead of using the Click event, have your ViewModel expose a Command that can be invoke directly on the databound VM.
Here's a simplified example from my United Nations News OSS WP7 app: (XAML, C#)
And here's another simplified sample of that same idea used in my Neurons WP7 OSS project: (XAML, C#)
I would also recommend MVVM, but it can be simplified. No need to go to the extreme of having a ViewModel for every object. The key is to bind the command to the DataContext of your ItemsControl (eg ListBox).
Let's assume that your ItemTemplate is for a ListBox, the ListBox has it's ItemsSource property bound to your ViewModel. Your xaml would look like this:
Your ViewModel, would then have the property
Songs
, that is a collection of your model object. It also has an ICommandAddToPlaylistCommand
. As I've said before, my favorite implementation of ICommand is the DelegateCommand from the PNP team.