Bind a button to a command (Windows Phone 7.5)

旧城冷巷雨未停 提交于 2019-12-03 02:31:54

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
                }));
        }
    }
}
Shawn Kendrot

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!