简体   繁体   中英

How do I bind a UISegmentedControl to a ViewModel command?

New to Xamarin and mvvmcross and I'm trying to bind a UISegmentedControl's ValueChanged event to a command in the ViewModel.

The viewModel command looks like this:

    public ICommand DonorCommand
    {
        get
        {
            return _donorCommand ?? (_donorCommand = new MvxCommand<string>(m =>
            {
                DonorIndividual.SetVisible(m);
                DonorBusiness.SetVisible(m);
                OnPropertyChanged(() => CurrentDonor);
            }));

        }
    }

My binding looks like this:

        this.CreateBinding(DonorType).For(c => c.ValueChanged).To((DonationViewModel vm) => vm.DonorCommand).Apply();

I get an error when I try to compile saying: Cannot convert 'lambda expression' to non-delegate type 'string' (CS1660)

So I tried to make a new command in the ViewModel of type int instead of string (after-all who looks at the text of a multi-part control for what to do?):

    private ICommand _donorTypeCommand;
    public ICommand DonorTypeCommand
    {
        get
        {
            return _donorCommand ?? (_donorCommand = new MvxCommand<int>(m =>
                {
                    // break here to see what's happening
                    OnPropertyChanged(() => CurrentDonor);
                }));

        }
    }

With this as the binding:

        this.CreateBinding(DonorType).For(c => c.ValueChanged).To((DonationViewModel vm) => vm.DonorTypeCommand).Apply();

I get the same error. (verified it complains about type 'string' in each case) Not sure what that mean How can I do this binding?

it's because it is trying to infer your command type ( <string> ) to ValueChanged , which is not a string property.

so, you may want to have a look at this :

http://fetchmytip.blogspot.be/2015/02/ios-uisegmentedcontrol-custom-binding.html

the trick is to create a default target binding for all UISegmentedControls that will automatically bind to the value of UISegmentedControl.SelectedSegment when it changes, in your case, your command will have to be of type <int> then (like .SelectedSegment)

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