Event Handlers on DataTemplate inside ItemsControl

You need to bind the Button to a Command your ItemsControl's DataContext.

Search for Command in WPF : ( A Common implementation ) :

public class RelayCommand<T> : IRelayCommand
{
    private Predicate<T> _canExecute;
    private Action<T> _execute;

    public RelayCommand(Action<T> execute, Predicate<T> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    private void Execute(T parameter)
    {
        _execute(parameter);
    }

    private bool CanExecute(T parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public bool CanExecute(object parameter)
    {
        return parameter == null ? false : CanExecute((T)parameter);
    }

    public void Execute(object parameter)
    {
        _execute((T)parameter);
    }

    public event EventHandler CanExecuteChanged;

    public void RaiseCanExecuteChanged()
    {
        var temp = Volatile.Read(ref CanExecuteChanged);

        if (temp != null)
            temp(this, new EventArgs());
    }
}

In your ViewModel ( The ItemsControl's DataContext , I Hope :) )

   private RelayCommand<FoodItem> _addToGroceriesCommand;
   public ICommand AddToGroceriesCommand
   {
        get
        {
            if (_addToGroceriesCommand == null)
            {
                _addToGroceriesCommand = new RelayCommand<FoodItem>(OnAddToGroceries);                    
            }
            return _addToGroceriesCommand;
        }
    }

   public void OnAddToGroceries(FoodItem newItem)
   {

   }

XAML :

   <ItemsControl ItemsSource="{Binding MyItemList}">
      <ItemsControl.ItemsTemplate>
         <DataTemplate>
             <Button Content="Buy" 
                     Command="{Binding Path=DataContext.AddToGroceriesCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
                     CommandParameter="{Binding}" />
         </DataTemplate> 
      </ItemsControl.ItemsTemplate>
   </ItemsControl> 

You should never use events in DataTemplates this will make you use casting and then blow a hole in the whole MVVM pattern. A button has the Command property and you should Bind that property to a command inside your MyItem ViewModel.

If you still need to use an event (for instance you cant bind MouseDown to a command) you shoudl use the EventToCommadn Behaviour which allows you to bind an event to a command. You can read about it here: http://msdn.microsoft.com/en-us/magazine/dn237302.aspx

Tags:

C#

Wpf

Mvvm