使用命令将参数传递到viewmodel

时间:2016-02-25 11:07:19

标签: c# wpf xaml mvvm data-binding

我无法将视图中的参数发送到我的viewmodel。

View.xaml

在我看来,我有以下内容:

<TextBox
    MinWidth="70"
    Name="InputId"/>

<Button 
    Command="{Binding ButtonCommand}"
    CommandParameter="{Binding ElementName=InputId}"
    Content="Add"/>

View.xaml.cs

public MyView()
{
    InitializeComponent();
}

public MyView(MyViewModel viewModel) : this()
{
    DataContext = viewModel;
}

MyViewModel.cs

public class MyViewModel : BindableBase
{
    public ICommand ButtonCommand { get; private set; }

    public MyViewModel()
    {
        ButtonCommand = new DelegateCommand(ButtonClick);
    }

    private void ButtonClick()
    {
        //Read 'InputId' somehow. 
        //But DelegateCommand does not allow the method to contain parameters.
    }
}

当我点击按钮到我的视图模型时,如何传递InputId的任何建议?

2 个答案:

答案 0 :(得分:11)

您需要将<object>添加到您的委托命令中,如下所示:

public ICommand ButtonCommand { get; private set; }

     public MyViewModel()
        {
            ButtonCommand = new DelegateCommand<object>(ButtonClick);
        }

        private void ButtonClick(object yourParameter)
        {
            //Read 'InputId' somehow. 
            //But DelegateCommand does not allow the method to contain parameters.
        }

您是否希望将文本框的文本更改为xaml:

CommandParameter="{Binding Text,ElementName=InputId}" 

答案 1 :(得分:3)

要正确实施ICommand / RelayCommand,请查看此MSDN页面。

要点:

public class RelayCommand : ICommand
{
    readonly Action<object> _execute;
    readonly Func<bool> _canExecute;

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public RelayCommand(Action<object> execute, Func<bool> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }


    public bool CanExecute(object parameter)
    {
        return _canExecute == null || _canExecute.Invoke();
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

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

} 


public MyViewModel()
{
    ButtonCommand = new RelayCommand(ButtonClick);
}

private void ButtonClick(object obj)
{
    //obj is the object you send as parameter.
}