【发布时间】:2015-09-20 23:20:57
【问题描述】:
所以,我有一个元素,它有一个带有 2 个参数的命令要传递。
我之前用我找到的一段 sn-p 代码做到了这一点,但我终生无法记住如何做到这一点或再次找到它。
所以,这里是我之前创建的多值转换器:
public class MultiValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType,
object parameter, CultureInfo culture)
{
return values.Clone();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return (value as string).Split(' ');
}
}
现在,我只需在 ICommand 中分配我想要调用的函数。我通常使用类似于以下的行:
enemyPopupTooltip = new RelayCommand(param => this.EnemyPopupTooltipEx(param),null);
但是,当它的多值时,这将不起作用。如何使用我的中继命令通过多值转换器将 2 个参数传递到我的函数中?
作为参考,这里是 relaycommand 类中的所有内容:
public class RelayCommand : ICommand
{
/// <summary>
/// Initializes a new instance of the <see cref="RelayCommand"/> class.
/// </summary>
/// <param name="execute">The execute.</param>
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RelayCommand"/> class.
/// </summary>
/// <param name="execute">The execute.</param>
/// <param name="canExecute">The can execute.</param>
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
/// <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(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 null.</param>
public void Execute(object parameter)
{
_execute(parameter);
}
/// <summary>
/// Action
/// </summary>
private readonly Action<object> _execute;
/// <summary>
/// Predicate
/// </summary>
private readonly Predicate<object> _canExecute;
【问题讨论】:
-
那个链接的问题没有显示在 MyViewModel.ZoomCommand 中会写什么,这就是我正在努力解决的问题:(
-
第二个方法:你不能将所需的参数绑定到某些 ViewModel 属性吗?然后你只需在你的方法中调用 VM 属性
标签: c# wpf mvvm multibinding relaycommand