gpt4 book ai didi

c# - 将参数传递给 MVVM 命令

转载 作者:可可西里 更新时间:2023-11-01 07:50:38 27 4
gpt4 key购买 nike

有谁知道如何使用 CommandHandler 将参数传递给 Command?假设我想从 XAML 传递字符串硬编码值。我知道如何从 XAML 传递,但不知道如何在后面的 MVVM 代码中处理它。如果不需要传递任何参数,下面的代码可以正常工作。

public ICommand AttachmentChecked
{
get
{
return _attachmentChecked ?? (_attachmentChecked = new CommandHandler(() => ExecuteAttachmentChecked(), CanExecuteAttachmentChecked()));
}
}

private void ExecuteAttachmentChecked()
{
}

private bool CanExecuteAttachmentChecked()
{
return true;
}

命令处理程序:

public class CommandHandler : ICommand
{
private Action _action;
private bool _canExecute;

public CommandHandler(Action action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}

public bool CanExecute(object parameter)
{
return _canExecute;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
_action();
}
}

最佳答案

你需要改变两件事

1.Change your Commandhandler to accept parameter

 public class CommandHandler : ICommand
{
private Action<object> _action;
private bool _canExecute;
public CommandHandler(Action<object> action, bool canExecute)
{
_action = action;
_canExecute = canExecute;
}

public bool CanExecute(object parameter)
{
return _canExecute;
}

public event EventHandler CanExecuteChanged;

public void Execute(object parameter)
{
_action(parameter);
}
}

2.Change the method to accept the CommandParameter:

public ICommand AttachmentChecked
{
get
{
return _attachmentChecked ?? (_attachmentChecked = new CommandHandler(param => ExecuteAttachmentChecked(param), CanExecuteAttachmentChecked()));
}
}

private void ExecuteAttachmentChecked(object param)
{
//param will the value of `CommandParameter` sent from Binding
}

private bool CanExecuteAttachmentChecked()
{
return true;
}

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

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