如何将CommandParameters传递给ViewModel?

时间:2012-02-26 15:14:11

标签: silverlight windows-phone-7 xaml data-binding mvvm

我有一个命令,应该在执行时切换当前视图。我将此命令绑定到我的按钮,如下所示:

<Button Style="{StaticResource TextButton}" Command="{Binding ViewModel:MainViewModel.OpenItemCommand}" CommandParameter="{Binding Link}"/>

我想将Link(当前所选文章的链接)传递给我的命令。我的命令定义如下:

public class Command : ICommand
{
    public event EventHandler CanExecuteChanged;

    readonly Predicate<Object> _canExecute;
    readonly Action<Object> _executeAction;

    public Command(Predicate<Object> canExecute, Action<object> executeAction)
    {
        _canExecute = canExecute;
        _executeAction = executeAction;
    }
    public bool CanExecute(object parameter)
    {
        if (_canExecute != null)
            return _canExecute(parameter);
        return true;
    }

    public void UpdateCanExecuteState()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, new EventArgs());
    }

    public void Execute(object parameter)
    {
        if (_executeAction != null)
            _executeAction(parameter);
        UpdateCanExecuteState();
    }
}

在我的ViewModel中,我有这个:

public ICommand OpenItemCommand
{
    get
    {
        if (_openItemCommand == null)
        {
            _openItemCommand = new Command.Command(
                p => true,
                p => OpenItem(_HOW_DO_I_GET_THE_PARAMETER?_)
            );
        }
        return _openItemCommand;
    }
    set 
    {
        if (_openItemCommand != value)
        {
            _openItemCommand = value;
            RaisePropertyChanged("OpenItemCommand");
        }
    }
}

private void OpenItem(Uri link)
{
    throw new NotImplementedException();
}

当我创建命令时,我需要将命令参数(链接)传递给Execute方法。但是我如何得到这个的价值呢?我在XAML中定义了CommandParameter,但我不知道如何访问它。

我真的搜索了大量的网站,但我找不到答案。

2 个答案:

答案 0 :(得分:1)

替换

 p => OpenItem(_HOW_DO_I_GET_THE_PARAMETER?_)

 p => OpenItem(p)

p代表的内容:参数

答案 1 :(得分:1)

你应该看一下Prism的DelegateCommand或MVVM light的RelayCommand的实现。有了这些,您可以编写如下代码:

public class ViewModel
{
    public ViewModel()
    {
        OpenItemCommand = new RelayCommand<string>(OpenItem);
    }

    public RelayCommand<string> OpenItemCommand { get; private set; }

    private void OpenItem(string link)
    {
        Debug.WriteLine(link);
    }
}

其中string在这种情况下是参数的类型。

我不确定链接参数的来源,但如果它来自控件,则控件的值可以绑定到视图模型的属性,然后您不需要参数,例如:

public class ViewModel
{
    public ViewModel()
    {
        OpenItemCommand = new RelayCommand(OpenItem);
    }

    public RelayCommand OpenItemCommand { get; private set; }

    public string Link { get; set; }

    private void OpenItem()
    {
        Debug.WriteLine(Link);
    }
}