Firing RelayCommand from CodeBehind bound to VM

Houman picture Houman · Nov 9, 2010 · Viewed 10.3k times · Source

I wonder if I can create a RelayCommand on my ViewModel like this:

public RelayCommand<IList<VectorViewModel>> MyCommand { get; set; }

ctor:

MyCommand = new RelayCommand<IList<VectorViewModel>>(DoSomething);

And from the Code behind XAML, I get the selected rows from a DataGrid and put them into a List.

if (xamDatagridVector.SelectedItems.Records.Count >= 3)
{
                var list = new List<VectorViewModel>();
                foreach (DataRecord record in xamDatagridVector.SelectedItems.Records)
                {
                    list.Add((VectorViewModel)record.DataItem);
                }
}

At this stage I would like to send the List back to the ViewModel by using that RelayCommand I had created earlier. Would that be possible to create a RelayCommand in code and Bind it to the ViewModel's command and fire it off?

What alternative way is there? I could of course use the weak-referenced Messenger class in MVVM-Light, but something I dont like there is that it will send it to all subscribers of that call, and not only the underlying ViewModel (Its deadly using Messenger when you have several instances of the same View within TabControls)

I hope someone has an idea to keep me going, Many Thanks, Kave

Answer

Thomas Levesque picture Thomas Levesque · Nov 9, 2010

Just call the Execute method of the command after checking the result of CanExecute:

var viewModel = (MyViewModel)DataContext;
if (viewModel.MyCommand.CanExecute(list))
    viewModel.MyCommand.Execute(list);