简体   繁体   中英

Xamarin.IOS : MVVMCross Passing parameter from view to ViewModel

I am using MVVMCross for my xamarin ios project. From my custom cell view, I want to pass a parameter to its view model. is it possible using MVVMCross?

I tried using CommandParameter property but it didn't work. Is it possible to pass parameters from view to viewmodel, If yes can someone provide a snippet?

Thank you

Update

My cell has button and on button click I want to know the cell index of the button being clicked to perform the operation. I am using the following code to do that.

this.DelayBind(() =>
{
    var bSet = this.CreateBindingSet<MyeCell, SomeViewModel>();
    bSet.Bind(cellIndex).To(vm => vm.index);
    bSet.Bind(UserPostBtn).To(vm => vm.EditPhotoCommand);
    bSet.Apply();
});

I tried using delaybind to connect view and viewmodel but on button clickm I am getting the following error:

invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.

You should be able to pass parameters to your ViewModel via a command using the MvxCommandParameterValueConverter .

String name approach:

bSet
    .Bind(UserPostBtn)
    .To(vm => vm.EditPhotoCommand)
    .WithConversion("CommandParameter", cellIndex);

Typed name approach:

bSet
    .Bind(UserPostBtn)
    .To(vm => vm.EditPhotoCommand)
    .WithConversion(new MvxCommandParameterValueConverter(), cellIndex);

Extension method approach:

bSet
    .Bind(MainButton)
    .To(vm => vm.EditPhotoCommand)
    .CommandParameter(cellIndex);

Then in your ViewModel receive the passed parameter.

IMvxCommand _editPhotoCommand;
public IMvxCommand EditPhotoCommand =>
    _editPhotoCommand ?? (_editPhotoCommand = new MvxCommand<int>(EditPhotoExecution));

private void EditPhotoExecution(int index)
{
    // do stuff
}

Update:

MvvmCross also provides an extension method, CommandParameter , that allows you to just pass in the command parameter and it will handle the creation of the MvxCommandParameterValueConverter .

Please have a look at the official documentation for MvvmCross and how to work with UITableViews and UITableViewCells.

Basically, your MvxTableViewSource subclass gets notified about what cell got selected. Now it is just a matter of checking your model and matching the index...

If you need to know what text was entered or switch was flipped in you cell, you should consider using a binding between your cell subclass and your cell source. Make sure to use DelayBind in your UITableViewCell subclass.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM