将按钮绑定到命令(Windows Phone 7.5)

Bar*_*sen 12 c# mvvm icommand windows-phone-7

我正在使用一些简单的数据绑定我的Windows-phone应用程序.我已经创建了一个基于MvvM编程方法的应用程序.我正在努力的应用程序也可以通过MvvM方法工作.因为我想让我的代码尽可能地保持干​​净,所以我正在寻找一种方法来在我的viewmodel或mainviewmodel中进行"按钮点击事件"(通常在代码隐藏页面中发生).

我已经在互联网上搜索了Icommand界面的简单解释,因为我相信这是一条路.我发现的解释有问题,其中一些是基于使用CommandRelay函数的MvvMlight工具包.我不想使用MvvM light工具包,因为我想先了解自己.我发现的其他教程是由过度热情的开发人员编写的,它们会给你一些过多的信息.

所以基本上.有人能告诉我绑定到按钮的Icommand的最简单版本有效吗?

Jay*_*Jay 21

在你的XAML中:

<Button Content="My Button" Command="{Binding MyViewModelCommand}" />
Run Code Online (Sandbox Code Playgroud)

在您的视图模型中:

public class MyViewModel
{

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

    public ICommand MyViewModelCommand { get; private set; }

    private void DoSomething()
    {
        // no, seriously, do something here
    }
}
Run Code Online (Sandbox Code Playgroud)

INotifyPropertyChanged和其他视图模型的愉快.
在视图模型中构建命令的另一种方法显示在本答案的底部.

现在,你需要一个实现ICommand.我建议从这样简单的东西开始,并根据需要扩展或实现其他功能/命令:

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;
}
Run Code Online (Sandbox Code Playgroud)

以下是布局视图模型的另一种方法:

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