locked
passing a void with no parameters method to a generic RelayCommand RRS feed

  • Question

  • hi 

    i want to pass this method to a RelayComman

    the method;

    public void method1 ()
    {
        // TO DO
    }

    like this;

    command1 = new RelayCommand(method1);

    but it always gives me error.

    here is RelayCommand Implentaion;

     public class RelayCommand<T>: ICommand
        {
            #region Fields
    
            readonly Action<T> _execute = null;
            readonly Predicate<T> _canExecute = null;
    
            #endregion
    
            #region Constructors
    
            /// <summary>
            /// Initializes a new instance of <see cref="DelegateCommand{T}"/>.
            /// </summary>
            /// <param name="execute">Delegate to execute when Execute is called on the command.  This can be null to just hook up a CanExecute delegate.</param>
            /// <remarks><seealso cref="CanExecute"/> will always return true.</remarks>
            public RelayCommand(Action<T> execute) : this(execute, null)
            {
    
            }
    
            /// <summary>
            /// Creates a new command.
            /// </summary>
            /// <param name="execute">The execution logic.</param>
            /// <param name="canExecute">The execution status logic.</param>
            public RelayCommand(Action<T> execute, Predicate<T> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
    
                _execute = execute;
                _canExecute = canExecute;
            }
    
            #endregion
    
            #region ICommand Members
    
            ///<summary>
            ///Defines the method that determines whether the command can execute in its current state.
            ///</summary>
            ///<param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to null.</param>
            ///<returns>
            ///true if this command can be executed; otherwise, false.
            ///</returns>
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute((T)parameter);
            }
    
            ///<summary>
            ///Occurs when changes occur that affect whether or not the command should execute.
            ///</summary>
            public event EventHandler CanExecuteChanged
            {
                add { CommandManager.RequerySuggested += value; }
                remove { CommandManager.RequerySuggested -= value; }
            }
    
            ///<summary>
            ///Defines the method to be called when the command is invoked.
            ///</summary>
            ///<param name="parameter">Data used by the command. If the command does not require data to be passed, this object can be set to <see langword="null" />.</param>
            public void Execute(object parameter)
            {
                _execute((T)parameter);
            }
    
            #endregion
    
    
        }

    if i give method1 a parameters it works,

    public void method2 (object p)
    {
        // p won't use.
    }
    
    /////////////////////
    command2 = new RelayCommand<object>(method2);

    but i want to use method1

    thanks in advance, any help will be appreciated.
    • Edited by essamce Wednesday, December 4, 2019 6:51 PM
    Wednesday, December 4, 2019 6:49 PM

Answers

  • Hi,

    Your code must take parameters, you can use it like this:

     private ICommand _command2;
         
            public ICommand command2
            {
                get
                {
                    return _command2 ?? (_command2 = new RelayCommand<object>(
                     
                           cm2Click,IsPrintAndExportEnabled 
                       ));
                }
            }
         
    
            public void cm2Click(object arg)
            {
                MessageBox.Show("CM2 Clicked!");
            }
            private bool IsPrintAndExportEnabled(object arg)
            {
                return true;
            }

    or use 

     public class RelayCommand : ICommand
        {
            public RelayCommand(Action execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action execute, Func<bool> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
    
                _execute = execute;
                _canExecute = canExecute;
            }
    
            [DebuggerStepThrough]
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute();
            }
            public event EventHandler CanExecuteChanged
            {   
                add { }
                remove { }
          
            }
    
            public void Execute(object parameter)
            {
                _execute();
            }
    
            readonly Action _execute;
            readonly Func<bool> _canExecute;
        }

     private ICommand _command2;
            public ICommand command2
            {
                get
                {
                    if (this._command2 == null)
                    {
                        this._command2 = new RelayCommand(
                            () => this.cm2Click(),
                            () => this.IsPrintAndExportEnabled());
                    }
    
                    return this._command2;
                }
                set { }
            }
    
    
            public void cm2Click()
            {
                MessageBox.Show("CM2 Clicked!");
            }
            private bool IsPrintAndExportEnabled()
            {
                return true;
            }

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    • Edited by Alex Li-MSFT Thursday, December 5, 2019 5:53 AM
    • Marked as answer by essamce Saturday, December 14, 2019 6:13 AM
    Thursday, December 5, 2019 5:48 AM
  • Try this:

    command1 = new RelayCommand<object>( ( _ ) => method1( ) );

     

    Or add another constructor:

    public RelayCommand( Action a ) : this( _ => a( ) )

    {

     

    }

    • Edited by Viorel_MVP Wednesday, December 4, 2019 9:21 PM
    • Marked as answer by essamce Saturday, December 14, 2019 6:14 AM
    Wednesday, December 4, 2019 9:17 PM

All replies

  • Try this:

    command1 = new RelayCommand<object>( ( _ ) => method1( ) );

     

    Or add another constructor:

    public RelayCommand( Action a ) : this( _ => a( ) )

    {

     

    }

    • Edited by Viorel_MVP Wednesday, December 4, 2019 9:21 PM
    • Marked as answer by essamce Saturday, December 14, 2019 6:14 AM
    Wednesday, December 4, 2019 9:17 PM
  • Hi,

    Your code must take parameters, you can use it like this:

     private ICommand _command2;
         
            public ICommand command2
            {
                get
                {
                    return _command2 ?? (_command2 = new RelayCommand<object>(
                     
                           cm2Click,IsPrintAndExportEnabled 
                       ));
                }
            }
         
    
            public void cm2Click(object arg)
            {
                MessageBox.Show("CM2 Clicked!");
            }
            private bool IsPrintAndExportEnabled(object arg)
            {
                return true;
            }

    or use 

     public class RelayCommand : ICommand
        {
            public RelayCommand(Action execute)
                : this(execute, null)
            {
            }
    
            public RelayCommand(Action execute, Func<bool> canExecute)
            {
                if (execute == null)
                    throw new ArgumentNullException("execute");
    
                _execute = execute;
                _canExecute = canExecute;
            }
    
            [DebuggerStepThrough]
            public bool CanExecute(object parameter)
            {
                return _canExecute == null ? true : _canExecute();
            }
            public event EventHandler CanExecuteChanged
            {   
                add { }
                remove { }
          
            }
    
            public void Execute(object parameter)
            {
                _execute();
            }
    
            readonly Action _execute;
            readonly Func<bool> _canExecute;
        }

     private ICommand _command2;
            public ICommand command2
            {
                get
                {
                    if (this._command2 == null)
                    {
                        this._command2 = new RelayCommand(
                            () => this.cm2Click(),
                            () => this.IsPrintAndExportEnabled());
                    }
    
                    return this._command2;
                }
                set { }
            }
    
    
            public void cm2Click()
            {
                MessageBox.Show("CM2 Clicked!");
            }
            private bool IsPrintAndExportEnabled()
            {
                return true;
            }

    Best Regards,

    Alex


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    • Edited by Alex Li-MSFT Thursday, December 5, 2019 5:53 AM
    • Marked as answer by essamce Saturday, December 14, 2019 6:13 AM
    Thursday, December 5, 2019 5:48 AM
  • ( _ => a( ) )
    could you please rewrite this part without underscore cuz im not familiar with discard variables.
    Saturday, December 14, 2019 6:22 AM
  • ( _ => a( ) )
    could you please rewrite this part without underscore cuz im not familiar with discard variables.

    Use some name instead of ‘_’:

       ( x => a( ) )


    Saturday, December 14, 2019 8:20 AM