将参数通过命令传递到视图模型

5

我在视图和视图模型之间传递参数遇到了问题。

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个回答

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
这太棒了!谢谢。 - Rasmus Bækgaard
4
谷歌搜索了30分钟后,这绝对是最好的解释。谢谢! - dvdhns

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接