如何快速實現一個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;
    }

實現自定義的命令

在方法中直接關閉窗口。this

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}}"
相關文章
相關標籤/搜索