ICommand接口

WPF 中的命令是通过实现 ICommand 接口创建的。ICommand 的 WPF 实现是 RoutedCommand 类。

  WPF 中的主要输入源是鼠标、键盘、墨迹和路由命令。更加面向设备的输入使用 RoutedEvent 来通知应用程序页中的对象已发生了输入事件。

ICommand接口只要是用于绑定Button等的点击事件,当数据改变的时候,会做出一些相应的通知,

当继承ICommand接口后,下面的方法则需要实现,它们之间的关系如图所示:

定义一个类实现ICommand接口

   public class DelegateCommand : ICommand
    {
        public Action<object> ExecuteAction { get; set; }
        public Func<object,bool> CanExecuteFunc { get; set; }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            if (CanExecuteFunc == null)
                return true;
            return
                CanExecuteFunc(parameter);
        }

        public void Execute(object parameter)
        {
            if (ExecuteAction == null)
                return;
            ExecuteAction(parameter);
        }
    }

在调用类中添加方法

public MainWindow()
        {
            InitializeComponent();

            AddCommand = new DelegateCommand();
            AddCommand.ExecuteAction = (para)=>
            {
                MessageBox.Show("我是按钮");
            };
        }
        public DelegateCommand AddCommand { get; set; }

在vm中command的绑定代码

<Button Content="点击我" Command="{Binding AddCommand}" />

 

posted @ 2015-09-14 08:22  lunawzh  阅读(1164)  评论(0编辑  收藏  举报