2

我正在尝试使用我的命令传递命令参数。我有一般工作的命令,但传递参数对我来说似乎并不顺利。

我正在尝试从我的 XAML 中的分层数据传递 UserName 属性。我在这里做错了什么。

我收到并尝试使用命令语句进行编译时出错:

无法从“lambda 表达式”转换为“System.Action”

<HierarchicalDataTemplate 
    DataType="{x:Type viewModel:UsersViewModel}" 
    ItemsSource="{Binding Children}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding UserName}">
            <TextBlock.ContextMenu>
                    <ContextMenu>
                        <MenuItem Header="Edit" Command="{Binding EditCommand}" CommandParameter="{Binding UserName}"/>
                        <MenuItem Header="Delete"/>
                    </ContextMenu>
                </TextBlock.ContextMenu>
        </TextBlock>
    </StackPanel>
</HierarchicalDataTemplate>
private RelayCommand _editCommand;
    public ICommand EditCommand
    {
        get
        {
            if (_editCommand== null)
            {
                _editCommand= new RelayCommand(param => this.LoadUser(object parameter));
            }
            return _editCommand;
        }
    }

    public void LoadUser(object username)
    {

    } 

中继命令类

public class RelayCommand : ICommand
{
    #region Fields

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

    #endregion // Fields

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    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
}

谢谢您的帮助!

4

2 回答 2

3

您不应调用该方法,而应将其作为参数传递。new RelayCommand(param => this.LoadUser(object parameter));只需更换new RelayCommand(this.LoadUser);

类似的问题: RelayCommand lambda syntax question

于 2012-02-06T22:50:56.010 回答
3
new RelayCommand(param => this.LoadUser(object parameter));

这不应该是:

new RelayCommand(param => this.LoadUser(param));
于 2012-02-06T22:51:53.940 回答