How to bind Command to button in DataTemplate in Windows Store app (CSWindowsStoreAppCommandBindingInDataTemplate)

Introduction

This sample demonstrates how to bind command to button which in the DataTemplate in Windows Store app.

Note that we've upgraded this sample to universal Windows app, please download from the link below:

https://code.msdn.microsoft.com/How-to-bind-command-to-a-299f7759

For UWP version, see https://code.msdn.microsoft.com/How-to-bind-command-to-a-83568113.

Building the Sample

1.       Start Visual Studio 2012 and select File > Open > Project/Solution.

2.       Go to the directory in which you download the sample. Go to the directory named for the sample, and double-click the Microsoft Visual Studio Solution (.sln) file.

3.       Press F7 or use Build > Build Solution to build the sample.

Running the Sample

1.       Press F5 to debug the app, this screen will display. Every item in the GridView contains a 'Delete' button.

 

 

 

2.       Please click the 'Delete' button, corresponding item will be deleted from GridView.

 

 

 

Using the Code

The code below shows how to implement ICommand interface.

C#
Edit|Remove
public interface IDelegateCommand : ICommand
{
    void RaiseCanExecuteChanged();
}


 public class DelegateCommand:IDelegateCommand
 {
     Action<object> execute;
     Func<object, bool> canExecute;


     #region Constructors
     public DelegateCommand(Action<object> execute, Func<object, bool> canExecute)
     {
         this.execute = execute;
         this.canExecute = canExecute;
     }


     public DelegateCommand(Action<object> execute)
     {
         this.execute = execute;
         this.canExecute = this.AlwaysCanExecute;
     }
     #endregion
    
     #region IDelegateCommand
     public void RaiseCanExecuteChanged()
     {
         if (CanExecuteChanged != null)
         {
             CanExecuteChanged(this, EventArgs.Empty);
         }
     }


     public bool CanExecute(object parameter)
     {
         return canExecute(parameter);
     }


     public event EventHandler CanExecuteChanged;


     public void Execute(object parameter)
     {
         execute(parameter);
     }
     #endregion


     bool AlwaysCanExecute(object param)
     {
         return true;
     }
 }

 

 

The code below shows how to define command in View Model.

C#
Edit|Remove
// This property will be bound to button's Command property for deleting item
public IDelegateCommand DeleteCommand { protected set; get; }


void ExecuteDeleteCommand(object param)
{
    int id = (Int32)param;
    Customer cus = GetCustomerById(id);
    if (cus != null)
    {
        Customers.Remove(cus);
    }
}


public CustomerViewModel()
{
    // create a DeleteCommand instance
    this.DeleteCommand = new DelegateCommand(ExecuteDeleteCommand);


    // Get data source
    Customers = InitializeSampleData.GetData();
}

 

 

The code below shows button command binding in xaml.

XAML
Edit|Remove
<GridView Name="CustomerGridView"
                          AutomationProperties.AutomationId="CustomerGridView"
                          AutomationProperties.Name="Customer Group"
                          ScrollViewer.VerticalScrollBarVisibility="Auto"
                          BorderThickness="1"
                          BorderBrush="Black"                                                    
                          ItemsSource="{Binding Customers}">
                    <GridView.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Width="200" Height="150">
                                <StackPanel Orientation="Horizontal" Margin="3,3,0,3">
                                    <TextBlock Text="Name:" Style="{StaticResource AppBodyTextStyle}" Margin="0,0,5,0"/>
                                    <TextBlock Text="{Binding Name}" Style="{StaticResource AppBodyTextStyle}"/>
                                </StackPanel>
                                <StackPanel Orientation="Horizontal" Margin="3,3,0,3">
                                    <TextBlock Text="Sex:" Style="{StaticResource AppBodyTextStyle}" Margin="0,0,5,0"/>
                                    <TextBlock Text="{Binding Sex, Converter={StaticResource SexConverter}}" Style="{StaticResource AppBodyTextStyle}"/>
                                </StackPanel>
                                <StackPanel Orientation="Horizontal" Margin="3,3,0,3">
                                    <TextBlock Text="Age:" Style="{StaticResource AppBodyTextStyle}" Margin="0,0,5,0"/>
                                    <TextBlock Text="{Binding Age}" Style="{StaticResource AppBodyTextStyle}"/>
                                </StackPanel>
                                <StackPanel Orientation="Horizontal" Margin="3,3,0,3">
                                    <TextBlock Text="Vip:" Style="{StaticResource AppBodyTextStyle}" Margin="0,0,5,0"/>
                                    <TextBlock Text="{Binding Vip}" Style="{StaticResource AppBodyTextStyle}"/>
                                </StackPanel>
                                <Button Content="Delete" Margin="0,5,0,0" Command="{Binding DataContext.DeleteCommand, ElementName=CustomerGridView}" CommandParameter="{Binding Id}"/>
                            </StackPanel>
                        </DataTemplate>
                    </GridView.ItemTemplate>
                    <GridView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <WrapGrid MaximumRowsOrColumns="8" VerticalChildrenAlignment="Top"
                      HorizontalChildrenAlignment="Left" Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </GridView.ItemsPanel>
                </GridView>

 

 

 

More Information

ICommand Interface

http://msdn.microsoft.com/en-us/library/windows/apps/system.windows.input.icommand

Commanding Overview

http://msdn.microsoft.com/en-us/library/windows/apps/ms752308