如何快速实现一个command

新建一个类,实现icoomand接口

定义一个委托,为测试方便,先不考虑CanExecute的情况。
越简单越好。
代码如下:

 public class ExitHandler : ICommand
    {
        private Action<object> execute;

        public  ExitHandler(Action<object> parameter)
        {
            this.execute = parameter;
        }

        public void Execute(object parameter)
        {
            this.execute(parameter);
        }

        public bool CanExecute(object parameter)
        {
            return true;

        }

        public event EventHandler CanExecuteChanged;
    }
    

实现自定义的命令

在方法中直接关闭窗口。

 public ExitHandler Exit
        {
            get { return _exit??(_exit=new ExitHandler((x) =>
            {
                Application.Current.Shutdown();
            })); }
            set { _exit = value; }
        }

xaml中的调用

<Button Content="Button" Command="{Binding Exit}" Height="23" HorizontalAlignment="Left" Margin="83,90,0,0" Name="button1" VerticalAlignment="Top" Width="75" />

DataContext的指定

 DataContext="{Binding RelativeSource={RelativeSource Self}}"
原文地址:https://www.cnblogs.com/hsapphire/p/8888235.html