7

是否有 RelayCommand 版本,因为 CommandManager 在 win8 Metro 应用程序中不可用?

4

3 回答 3

4

这里有一个版本。

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;
    } 
}
于 2012-09-18T23:49:42.897 回答
1

如果 Metro 中提供了 ICommand,则没有实现,尽管有几个版本可用,例如CodeProject上的这个。

于 2012-09-18T23:49:51.860 回答
0

Prism for Windows Store 应用程序现在可用,其中包含 DelegateCommand(实现 ICommand)以及 OnPropertyChanged 的​​实现。

于 2013-07-05T03:34:45.323 回答