Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firing RelayCommand from CodeBehind bound to VM

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

like image 505
Houman Avatar asked Nov 09 '10 17:11

Houman


1 Answers

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);
like image 188
Thomas Levesque Avatar answered Nov 13 '22 22:11

Thomas Levesque