Relay Command in windows 8 windows store app

后端 未结 3 1555
孤独总比滥情好
孤独总比滥情好 2021-02-15 23:01

Is there a version of RelayCommand, since CommandManager is not available in win8 metro apps?

3条回答
  •  悲哀的现实
    2021-02-15 23:59

    There is a version here.

    using System;
    using System.Diagnostics;
    
    #if METRO
    using Windows.UI.Xaml.Input;
    using System.Windows.Input;
    #else
    using System.Windows.Input;
    #endif
    
    namespace MyToolkit.MVVM
    {
    #if METRO
        public class RelayCommand : NotifyPropertyChanged, ICommand
    #else
        public class RelayCommand : NotifyPropertyChanged, ICommand
    #endif
        {
            private readonly Action execute;
            private readonly Func canExecute;
    
            public RelayCommand(Action execute)
                : this(execute, null) { }
    
            public RelayCommand(Action execute, Func canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
    
                this.execute = execute;
                this.canExecute = canExecute;
            }
    
            bool ICommand.CanExecute(object parameter)
            {
                return CanExecute;
            }
    
            public void Execute(object parameter)
            {
                execute();
            }
    
            public bool CanExecute 
            {
                get { return canExecute == null || canExecute(); }
            }
    
            public void RaiseCanExecuteChanged()
            {
                RaisePropertyChanged("CanExecute");
                if (CanExecuteChanged != null)
                    CanExecuteChanged(this, new EventArgs());
            }
    
            public event EventHandler CanExecuteChanged;
        }
    
        public class RelayCommand : ICommand
        {
            private readonly Action execute;
            private readonly Predicate canExecute;
    
            public RelayCommand(Action execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action execute, Predicate canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
    
                this.execute = execute;
                this.canExecute = canExecute;
            }
    
            [DebuggerStepThrough]
            public bool CanExecute(object parameter)
            {
                return canExecute == null || canExecute((T)parameter);
            }
    
            public void Execute(object parameter)
            {
                execute((T)parameter);
            }
    
            public void RaiseCanExecuteChanged()
            {
                if (CanExecuteChanged != null)
                    CanExecuteChanged(this, new EventArgs());
            }
    
            public event EventHandler CanExecuteChanged;
        } 
    }
    

提交回复
热议问题