在Windows 8 Windows Store应用程序中的Relay Command

7

在Win8 Metro应用程序中,由于CommandManager不可用,是否有RelayCommand的版本?

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;
    } 
}

2
只是想指出这个文件没有它所引用的“NotifyPropertyChanged”类,大多数人都知道如何重新创建它,但对于那些不知道的人来说,包含它可能会更好。 - Owen Johnson
2
@OwenJohnson 在这里找到了 NotifyPropertyChanged:https://mytoolkit.svn.codeplex.com/svn/Shared/MVVM/NotifyPropertyChanged.cs - N_A

1

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


0

现在可以使用适用于Windows Store应用的Prism,其中包含DelegateCommand(实现ICommand),以及OnPropertyChanged的实现。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接