gpt4 book ai didi

c# - 传递命令参数

转载 作者:行者123 更新时间:2023-12-04 15:52:56 29 4
gpt4 key购买 nike

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

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

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com