c# - 传递命令参数

标签 c# wpf xaml icommand relaycommand

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

我正在尝试从我的 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)
    {

    } 

RelayCommand 类

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
}

感谢您的帮助!

最佳答案

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

这不应该是:

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

关于c# - 传递命令参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9168389/

相关文章:

c# - WPF 应用程序中的 LINQ TO SQL 生成连接是关闭异常,有时

c# - 在 C# 中将 RichTextBox 绑定(bind)到 slider 控件

xaml - WP8-访问父级的datacontext

c# - 一张表或多张表,数据只有一列发生变化

c# - 错误 : Object must implement IConvertible

c# - 将光标设置在文本框的任何文本的末尾

c# - 使用 DataTable 的 DataGrid 中的 WPF 单个单元格颜色

c# - 制作一部分 TreeViewItem 包装

c# - 如何从另一个 .NET 程序使用交互式命令行程序

c# - 当应用程序在 WP 8.1 商店应用程序中恢复时,应用程序恢复事件不会触发