在View页面简单的添加一个Button控件

 <Button Name="btnTest" Content="Button Test" Command="{Binding TestCommand}"></Button>

自定义一个RelayCommand类,继承ICommand类

public class RelayCommand : ICommand

    {

        private Action _handler;

 

        //Action是一个委托方法,所有的放到都可以传递进来,在Execute中执行。       

        public RelayCommand(Action handler)       

        {           

            this._handler = handler;       

        }

 

        public bool CanExecute(object parameter)

        {

            return true;

        }

 

        //public event EventHandler CanExecuteChanged;

 

        public event EventHandler CanExecuteChanged

        {

            add { CommandManager.RequerySuggested += value; }

            remove { CommandManager.RequerySuggested -= value; }

        }

 

        public void Execute(object parameter)

        {

            _handler();

        }

}

定义ViewModel,使用ICommand

public class PersonViewModel
    {
        private ICommand _testCommand;
        public ICommand TestCommand
        {
            get
            {
               return _testCommand = new RelayCommand(TestMethod);            }
        }

 

              public void TestMethod()

{

      MessageBox.Show("hello world");

}

}

在View页面的后置代码中

简单的实例化一个ViewModel

 PersonViewModel personView = new PersonViewModel();

把当前页面的数据上下文和Viewmodel关联

this.DataContext = personView;

然后ViewModel和View就绑定好,ViewModel中的TestCommand命令就和页面上Button按钮绑定到了一起

运行模拟器,点击按钮就会执行TestCommand命令,弹出“hello world”对话框

 

如果控件没有Command属性,那么需要在后置代码中使用代码来绑定Command事件

如果CanExecute返回false,就会发现按钮控件呈现不可使用的灰色效果