在WPF中将命令参数传递给ViewModel中的方法

本文关键字:ViewModel 方法 命令 WPF 参数传递 | 更新日期: 2023-09-27 18:08:20

我正试图将CommandParameter传递给我的ViewModel中的方法。如何做到这一点?

private void Open(object sender)
{
    if (sender==this.objMainWindow.btnHistory)
    {
        objMainWindow.Container.Child = objHistory;
    }
    if (sender == this.objMainWindow.btnNew_Item)
    {
        objMainWindow.Container.Child = objNewItem;
    }
    if (sender == this.objMainWindow.btnSide_Effects)
    {
        objMainWindow.Container.Child = objSideEffect;
    }
}

这是我在ViewModel中的方法,我想通过CommandParameter。我使用CommandParameter按钮

在WPF中将命令参数传递给ViewModel中的方法

"ViewModel"暗含MVVM。如果你在做MVVM,你不应该把视图传递到视图模型中。一般在XAML:

中这样做
<Button Content="Edit" 
        Command="{Binding EditCommand}"
        CommandParameter="{Binding ViewModelItem}" >

然后在视图模型中:

private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
    get
    {
        return this._ViewModelItem;
    }
    set
    {
        this._ViewModelItem = value;
        RaisePropertyChanged(() => this.ViewModelItem);
    }
}
public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
    ... do something here...
}

显然,这只是为了说明这一点,如果您只有一个属性要编辑ViewModelItem,那么您就不需要将其作为命令参数传递。

只是使用数据绑定语法。例如,

<Button x:Name="btn" 
         Content="Click" 
         Command="{Binding ClickCmd}" 
         CommandParameter="{Binding ElementName=btn,Path=Content}" /> 

我们不仅可以使用数据绑定从视图模型中获取一些数据,还可以将数据传递回视图模型。在CommandParameter中,必须使用ElementName来显式声明绑定源

如果你特别想传递元素给viewmodel,你可以使用

 CommandParameter="{Binding ElementName=ManualParcelScanScreen}"

试试这个:

 public class MyVmBase : INotifyPropertyChanged
{
  private ICommand _clickCommand;
   public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler( MyAction));
        }
    }
    
       public void MyAction(object message)
    {
        if(message == null)
        {
            Notify($"Method {message} not defined");
            return;
        }
        switch (message.ToString())
        {
            case "btnAdd":
                {
                    btnAdd_Click();
                    break;
                }
            case "BtnEdit_Click":
                {
                    BtnEdit_Click();
                    break;
                }
            default:
                throw new Exception($"Method {message} not defined");
                break;
        }
    }
}
  public class CommandHandler : ICommand
{
    private Action<object> _action;
    private Func<object, bool> _canExecute;
    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action<object> action, Func<object, bool> canExecute)
    {
        if (action == null) throw new ArgumentNullException(nameof(action));
        _action = action;
        _canExecute = canExecute ?? (x => true);
    }
    public CommandHandler(Action<object> action) : this(action, null)
    {
    }
    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }
    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute(parameter);
    }
    public void Execute(object parameter)
    {
        _action(parameter);
    }
    public void Refresh()
    {
        CommandManager.InvalidateRequerySuggested();
    }
}

和xaml:

     <Button
    Command="{Binding ClickCommand}"
    CommandParameter="BtnEdit_Click"/>