Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MvxPickerViewModel Bind to Property of an Object

I have following code:

var pickerViewModel = new MvxPickerViewModel(this.mandantenPicker);
this.mandantenPicker.Model = pickerViewModel;
this.mandantenPicker.ShowSelectionIndicator = true;
mandantenAuswahlTextfield.InputView = this.mandantenPicker;

var set = this.CreateBindingSet<LoginView, LoginViewModel>();

set.Bind(pickerViewModel).For(p => p.SelectedItem).To(vm => vm.SelectedMandant);
set.Bind(pickerViewModel).For(p => p.ItemsSource).To(vm => vm.Mandanten);

set.Apply();

In the PickerView I don't have the expected values. Its showing the namespace of the object.

I'm binding to a list of "Mandants", a Mandant has FirstName/LastName. How can I set the "to be showed" value?

So something like:

set.Bind(pickerViewModel).For(p => p.ItemsSource).To(vm => vm.Mandanten)["FirstName"]; //stupid example but to show better what I mean/want
like image 517
eMi Avatar asked Feb 03 '26 09:02

eMi


1 Answers

The MvxPickerViewModel currently uses GetTitle() to work out what to display:

    public override string GetTitle(UIPickerView picker, int row, int component)
    {
        return _itemsSource == null ? "-" : RowTitle(row, _itemsSource.ElementAt(row));
    }

    protected virtual string RowTitle(int row, object item)
    {
        return item.ToString();
    }

from https://github.com/slodge/MvvmCross/blob/v3/Cirrious/Cirrious.MvvmCross.Binding.Touch/Views/MvxPickerViewModel.cs

If you wanted to customise the strings displayed, you could:

  • inherit from MvxPickerViewModel and provide an override for RowTitle:

    protected override string RowTitle(int row, object item)
    {
        return ((Mandant)item).FirstName;
    }
    
  • or override the ToString in your Mandant object

  • or provide and use some ValueConverters from IEnumerable<Mandant> to IEnumerable<WrappedMandant> and Mandant to WrappedMandant where WrappedMandant provides the ToString() implementation you want to use:

      public class WrappedMandant
      {
           public Mandant Mandant { get;set;}
           public override string ToString()
           {
               return Mandant.FirstName;
           }
      }
    

If you wanted to customise the picker cells displayed further, then you could also override GetView and them provide a custom cell for each Mandant

like image 173
Stuart Avatar answered Feb 05 '26 04:02

Stuart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!