将带有命令的参数传递到视图模型中

本文关键字:视图 模型 参数传递 命令 | 更新日期: 2023-09-27 18:36:13

我在将参数从我的视图发送到我的视图模型时遇到问题。

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

我的视图模型.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

将带有命令的参数传递到视图模型中

您需要像

这样将<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}" 

要正确实现 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.
}