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

时间:2015-08-18 05:38:32

标签: c# wpf mvvm icommand

我正在尝试将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的meyhod。我使用CommandParameter作为按钮。

4 个答案:

答案 0 :(得分:38)

"视图模型"意味着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,那么您就不需要将其作为命令参数传递。

答案 1 :(得分:6)

如果你特意将元素传递给viewmodel你可以使用

 CommandParameter="{Binding ElementName=ManualParcelScanScreen}"

答案 2 :(得分:0)

我个人只是使​​用.Tag属性如下:

<Button Content="Button" Click="Button_Click" Tag="{Binding .}"></Button>

然后为了获得整个对象:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        var btn = sender as Button;
        var myViewModel = btn.Tag as MyViewModel;
        ...
    }

答案 3 :(得分:0)

尝试一下:

A = [a, a, a, a, a, a] 
B = [a, a, b]

在xaml中:

 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();
    }
}