传递命令参数

时间:2012-02-06 22:37:16

标签: c# wpf xaml icommand relaycommand

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

我正在尝试从我的XAML中的Hierarchical Data传递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)
    {

    } 

RelayCommand Class

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
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:3)

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

new RelayCommand(this.LoadUser);即可

这里有类似的问题: RelayCommand lambda syntax problem

答案 1 :(得分:3)

new RelayCommand(param => this.LoadUser(object parameter));

不应该是:

new RelayCommand(param => this.LoadUser(param));