UIPickerView and MvvmCross

Mvvmcross is an open source cross platform mobile framework enabling Xamarin developers to maximize code reuse and, as stated in the name, allow using the Mvvm software architectural pattern to bind behavior directly to platform controls.

Recently, I have had to implement an UIPickerView and attach it to a UITextField as an InputView. MvvmCross is rich with custom controls and luckily and I was pleased to find that someone already thought about providing a ready to go implementation: MvxPickerView.

We will create a NamesViewModel and NamesViewController with one UITextField

In your ViewController, the code to create the Picker looks like this:

public override ViewDidLoad()
{
  var picker = new UIPickerView();
  var pickerViewModel = new MvxPickerViewModel(picker);
  picker.Model = pickerViewModel;
  picker.ShowSelectionIndicator = true;PickerTextField.InputView = picker;
}

In your NamesViewModel add the following Binding properties:

private string _selectedName;
public string SelectedName 
{
  get { return _selectedName; }
  set {SetProperty(ref _selectedName, value);}
}
private ObservableCollection<string> _namesCollection { get; set; }
public virtual ObservableCollection<string> NamesCollection 
{
  get { return _namesCollection; }
  set { SetProperty(ref _namesCollection, value); }
}

The we need to initialize the collection and feed it some values to be displayed by the picker:

public override Task Initialize()
{
    NamesCollection = new ObservableCollection() {"Karim", "John", "Peter"};
}

Back in your ViewController, we need to set the bindings so that the pickerModel knows where to source the data that it needs to display:

protected override void ViewDidLoad()
{
  base.ViewDidLoad();
  var picker = new UIPickerView();
  var pickerViewModel = new MvxPickerViewModel(picker);
  picker.Model = pickerViewModel;
  picker.ShowSelectionIndicator = true;
  PickerTextField.InputView = picker;

  //create the bindings
  this.CreateBinding(PickerTextField).To((NamesViewModel vm) => vm.SelectedName).Apply();
  this.CreateBinding(_pickerViewModel).For(p => p.ItemsSource).To((NamesViewModel vm) => vm.NamesCollection).Apply();
  this.CreateBinding(_pickerViewModel).For(p => p.SelectedItem).To((NamesViewModel vm) => vm.SelectedName).Apply();
}

And that’s it, you should be able to see the the pickerView bound to the collection of names that you have set in your ViewModel.

Happy coding!