casillas
casillas

Reputation: 16793

Pass parameter via ICommand

The following works if I do not pass anything from the View.

View.cs

ViewModel.ReloadCommand.Execute(null);

ViewModel.cs

public ICommand ReloadCommand
{
  get
   {
      return new MvxCommand(async () =>
         {
            await RefreshStudentList();
         });
    }
}

However I need to pass a parameter, I wonder how could I do that?

ViewModel.ReloadCommand.Execute(xxx);

ViewModel.cs

public ICommand ReloadCommand
{
  get
   {
      return new MvxCommand(async () =>
         {
            await RefreshStudentList(xxx);
         });
    }
}

Upvotes: 0

Views: 1262

Answers (4)

Igor
Igor

Reputation: 609

Not quite the answer you might be looking for but...

My understanding of Mvvm is that it reflects the state of the View and reacts to Commands from the View. Your parameter can be treated as State and as such should have its own Property on the ViewModel that it would be bound to. Thus your Command would not have to pass a parameter. This would also further de-couple the ViewModel from the View's implementation.

Upvotes: 0

Cheesebaron
Cheesebaron

Reputation: 24460

To do async operation MvvmCross also has a MvxAsyncCommand which also can take a parameter as the regular MvxCommand.

It looks something like this:

public ICommand ReloadCommand
{
    return new MvxAsyncCommand(DoAsyncStuff);
}

private Task DoAsyncStuff(MyType type)
{

}

Any command can be executed with a parameter like:

ViewModel.ReloadCommand.Execute(myParameter);

Upvotes: 3

Darren Christopher
Darren Christopher

Reputation: 4779

Instead of doing that, try initialize your ViewModel on your View first. Then, based on your code, the ICommand does only RefreshRoutesList function, so I will access the RefreshRoutesList directly from the View. To make the naming clear, I will use MyView.cs and MyViewModel.cs

MyView.cs

MyViewModel vm;
.
.
protected override void OnCreate(Bundle bundle)
{
    .... //other stuff
    vm = ViewModel as MyViewModel;
}

After doing that, you could call your function anywhere in your view using vm variable, i.e.

await vm.RefreshRoutesList(aParameter);

Hope this can help.

Upvotes: 0

Michael Gunter
Michael Gunter

Reputation: 12811

I'm not familiar with MvvmCross, but from what I can tell, it would be something like this:

public ICommand ReloadCommand
{
    get
    {
        return new MvxCommand<XXXType>(async (xxx) =>
            {
                await RefreshRoutesList(xxx);
            });
    }
}

Upvotes: 3

Related Questions