WPF自定义命令

WPF的自定义命令实现过程包括三个部分,定义命令、定义命令源、命令调用,代码实现如下:

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            
        }

        /// <summary>
        /// 自定义命令演示
        /// </summary>
        public void TestUserDefineCommand() {
            UserDefineCommandSource source = new UserDefineCommandSource();
            UserDefineCommand userCmd = new UserDefineCommand();
            source.Command = userCmd;
            source.CommandTarget = this;
        }
    }

    public class UserDefineCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;
        public bool CanExecute(object parameter)
        {
            throw new NotImplementedException();
        }
        public void Execute(object parameter)
        {
            
        }
    }

    public class UserDefineCommandSource : UserControl, ICommandSource
    {
        public ICommand Command { get; set; }
        public object CommandParameter { get; set; }
        public System.Windows.IInputElement CommandTarget { get; set; }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            base.OnMouseLeftButtonDown(e);  
            if (this.CommandTarget != null && this.Command != null)
                this.Command.Execute(this.CommandTarget);
        }
    }

  Button控件的定义如下:public abstract class ButtonBase : ContentControl, ICommandSource,因为实现了ICommandSource接口,因此,可以Button为命令源,可以为其设置命令。

posted @ 2018-02-08 11:48  Perfectionist  阅读(246)  评论(0编辑  收藏  举报