c# – Windows 8 Windows应用中的中继命令

前端之家收集整理的这篇文章主要介绍了c# – Windows 8 Windows应用中的中继命令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否有版本的RelayCommand,因为在win8 metro应用程序中没有CommandManager?

解决方法

有一个版本 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<RelayCommand>,ICommand
#endif
    {
        private readonly Action execute;
        private readonly Func<bool> canExecute;

        public RelayCommand(Action execute)
            : this(execute,null) { }

        public RelayCommand(Action execute,Func<bool> 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<T> : ICommand
    {
        private readonly Action<T> execute;
        private readonly Predicate<T> canExecute;

        public RelayCommand(Action<T> execute)
            : this(execute,null)
        {
        }

        public RelayCommand(Action<T> execute,Predicate<T> 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;
    } 
}

猜你在找的C#相关文章