WPF命令

命令基本元素及关系
WPF里已经有了路由事件,那为什么还需要命令呢?
因为事件指负责发送消息,对消息如何处理则不管,而命令是有约束力,每个接收者对命令执行统一的行为,比如菜单上的保存,工具栏上的保存都必须是执行同样的保存。

WPF命令必须要实现ICommand接口,以下为ICommand接口结构

using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows.Markup;
namespace System.Windows.Input
{
    public interface ICommand
    {
        //摘要:当出现影响是否应执行该命令的更改时发生。
        event EventHandler CanExecuteChanged;
        //摘要:定义用于确定此命令是否可以在其当前状态下执行的方法。
        //参数:此命令使用的数据。 如果此命令不需要传递数据,则该对象可以设置为 null。
        //返回结果:如果可以执行此命令,则为 true;否则为 false。
        bool CanExecute(object parameter);
        //摘要:定义在调用此命令时调用的方法。
        //参数:此命令使用的数据。 如果此命令不需要传递数据,则该对象可以设置为 null。
        void Execute(object parameter);
    }
}

ICommand接口实现

using System;
using System.Windows.Input;

namespace Micro.ViewModel
{
    public class DelegateCommand : ICommand
    {
        public Action<object> ExecuteCommand = null;
        public Func<object, bool> CanExecuteCommand = null;

        public event EventHandler CanExecuteChanged;
        public bool CanExecute(object parameter)
        {
            if (CanExecuteCommand != null)
            {
                return this.CanExecuteCommand(parameter);
            }
            else
            {
                return true;
            }
        }
        public void Execute(object parameter)
        {
            if (ExecuteCommand != null) this.ExecuteCommand(parameter);
        }
        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}

 

posted @ 2018-11-13 13:37  microsoftzhcn  阅读(606)  评论(0编辑  收藏  举报