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.
In my Mahjong game, an ItemsControl renders 144 stones (DataBound to 144 StoneViewModels):
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.
Take the following steps to access parent viewmodels
<ItemsControl x:Name="BoardItemsControl"
<Button
Command="{Binding DataContext.TapStoneCommand, ElementName=BoardItemsControl}"
CommandParameter="{Binding}"