Passing a parameter using RelayCommand defined in the ViewModel (from Josh Smith example)

后端 未结 6 500
既然无缘
既然无缘 2020-12-09 02:57

I would like to pass a parameter defined in the XAML (View) of my application to the ViewModel class by using the RelayCommand. I followed Josh Smith\'s excellent article o

6条回答
  •  粉色の甜心
    2020-12-09 03:36

    Here is a simple solution for the commandparameter as I was looking for help on the subject. I could not find anything online that was simple enough. The following solution works well when you are using a relaycommand. I had a few hyperlinks for which I needed to get the url value that was clicked using the command parameter.

    Step 1: In your relay command, create a simple property that will hold the parameter object value. You could call it parametervalue or any name that you prefer.

    public object ParameterValue
    {
      get;
      set;
    }
    

    Step 2: In the Execute Method of the RelayCommand class, set the value or the property created above to the parameter from the Execute method.

    readonly Action m_execute;       // Action to execute
    
    public void Execute(object parameter)
     {
       this.ParameterValue = parameter;
       m_execute(parameter);
     }
    
    
    

    Step 3: Now when you can bind the CommandParameter in xaml to any value you want to retrieve when the command is executed. example:

    
      
        
      
     
    

    If you have a command called chickenCommand, when executed you could access the parameter: chickenCommand.ParameterValue

    I hope this helps somebody. Thank you for all your previous help.

    提交回复
    热议问题