Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Relay Command in windows 8 windows store app

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

like image 313
GodsCrimeScene Avatar asked Sep 18 '12 23:09

GodsCrimeScene


2 Answers

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<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;
    } 
}
like image 85
N_A Avatar answered Sep 28 '22 20:09

N_A


There is no implementation if ICommand provided in Metro, although there are several versions available, such as this one on CodeProject.

like image 37
akton Avatar answered Sep 28 '22 22:09

akton