If your ViewModel has a list of buttons, how can each button invoke a command from the ViewModel? And how does the Command 'know' what button was clicked? How can we do this in Windows 8 and Windows Phone 8 without WPF's AncestorType?

Accessing parent ViewModel from DataTemplate in a Universal App.

In a post from the past I wrote about invoking control methods from a DataTemplate. Today you will learn how to invoke a ViewModel Command that is defined on the parent of your DataTemplate.

DataContext and ElementName

In my Mahjong game, an ItemsControl renders 144 stones (DataBound to 144 StoneViewModels):

mahjong

The XAML looks like this:

<ItemsControl x:Name="BoardItemsControl" ItemsSource="{Binding Stones}">
<ItemsControl.ItemTemplate>
<DataTemplate>
    <Button Template="{StaticResource ButtonControlTemplateStone}"

The DataContext of ItemsControl is a GameViewModel, which has the following Command:

public ICommand TapStoneCommand { get; set; }

TapStoneCommand=new DelegateCommand<StoneViewModel>(stone =>
{
});

To make a reference to the GameViewModel, use an ElementBinding to the ItemsControl. By using the ItemsControl’s DataContext, we have access to the Command like in the following code:

<ItemsControl x:Name="BoardItemsControl" ItemsSource="{Binding Stones}">
<ItemsControl.ItemTemplate>
<DataTemplate>
    <Button Template="{StaticResource ButtonControlTemplateStone}"
        Command="{Binding DataContext.TapStoneCommand, ElementName=BoardItemsControl}"
CommandParameter="{Binding}"

The way to access parent ViewModels in WinRT is to use DataContext and Element Binding. CommandParameter="{Binding}" passes the DataTemplate’s DataContext to the Command.

Summary

Take the following steps to access parent viewmodels

<ItemsControl x:Name="BoardItemsControl"
<Button
Command="{Binding DataContext.TapStoneCommand, ElementName=BoardItemsControl}"
CommandParameter="{Binding}"
Written by Loek van den Ouweland on 2015-01-31.
Questions regarding this artice? You can send them to the address below.