Bind a button to a command (Windows Phone 7.5)

To add to Jays answer:

My all time favorite is the DelegateCommand from the Patterns and Practices team @ Microsoft. Check out this post for more info.


In your XAML:

<Button Content="My Button" Command="{Binding MyViewModelCommand}" />

In your view-model:

public class MyViewModel
{

    public MyViewModel()
    {
        MyViewModelCommand = new ActionCommand(DoSomething);
    }

    public ICommand MyViewModelCommand { get; private set; }

    private void DoSomething()
    {
        // no, seriously, do something here
    }
}

INotifyPropertyChanged and other view-model pleasantries elided.
An alternative way to structure the command in your view-model is shown at the bottom of this answer.

Now, you'll need an implementation of ICommand. I suggest starting with something simple like this, and extend or implement other features/commands as necessary:

public class ActionCommand : ICommand
{
    private readonly Action _action;

    public ActionCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

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

    public event EventHandler CanExecuteChanged;
}

Here is an alternative way to layout your view-model:

public class MyViewModel
{
    private ICommand _myViewModelCommand;
    public ICommand MyViewModelCommand
    {
        get 
        {
            return _myViewModelCommand
                ?? (_myViewModelCommand = new ActionCommand(() => 
                {
                    // your code here
                }));
        }
    }
}