简体   繁体   中英

Pass String to method via CommandParameter

I would like to ask, is it possible to pass string value from view (xaml) to property in ViewModel?

I have Two tabs. First is "Process" and the second is "Non-Process". Depends on that string value RelayCommand will execute and fire method with DispatcherTimer (if Process then Dispatcher1, if Non-Process then Dispatcher2).

xaml:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="PreviewMouseDown" >
       <cmd:EventToCommand Command="{Binding EmployeeViewM.MeasurementEndExecution}"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

Can I use CommandParameter and CommandParameterValue to pass that string to the property?

Thank you for any suggestion

Yes you can, like below:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="PreviewMouseDown" >
        <cmd:EventToCommand Command="{Binding EmployeeViewM.MeasurementEndExecution}" CommandParameter="Process"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

And/OR

<i:Interaction.Triggers>
    <i:EventTrigger EventName="PreviewMouseDown" >
        <cmd:EventToCommand Command="{Binding EmployeeViewM.MeasurementEndExecution}" CommandParameter="Non-Process"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

Hopefully your RelayCommand (or ICommand implementation) is already accepting CommandParameter . Like below.

 public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> 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<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members


    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM