2016-05-31 145 views
0

我想问,是否可以通过传递字符串从view(xaml)到ViewModel中的属性的值?通过CommandParameter将字符串传递给方法

我有两个选项卡。首先是“过程”,第二个是“非过程”。取决于该字符串值RelayCommand将使用DispatcherTimer执行并激活方法(如果Process然后是Dispatcher1,如果Non-Process不是Dispatcher2)。

XAML:

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

我可以使用CommandParameterCommandParameterValue来传递的财产?

谢谢你的任何建议

+1

在问你是否可以,你试过吗? *当然*你可以使用'CommandParameter',它不能是'string',它可以是任何你想要的,并且可以绑定到你想要的任何属性。如果您有两个窗口,则首先可以传递字符串“process”,并在第二个“non-process”中传递。命令引发的方法有一个'object'类型的参数,它恰好是窗口传递给VM的参数。 –

+0

你试过什么_did?发生了什么?这与你想要的有什么不同?请提供一个很好的[mcve],清楚地表明你正在尝试做什么,以及准确描述你正在使代码工作的具体问题。 –

回答

0

当然可以,象下面这样:

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

和/或

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

希望您的RelayCommand(或ICommand实现)已经接受CommandParameter。如下所示。

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 
}