Search code examples
iosxamarinmvvmcross

How to bind to the title of a UISegmentedControl segment with MVVMCross?


Is it possible to bind a property of a view model to the title of a segment in UISegmentedControl?

I'm aware of the SetTitle() method, but not sure if it's possible to bind to this in MvvmCross.


Solution

  • Building off of Kiliman's answer to a similar question.

    Follow the first 2 steps from that answer. Then create the following custom binding builder.

    public class MyTouchBindingBuilder : MvxTouchBindingBuilder
    {
        protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
        {
            base.FillTargetFactories (registry);
    
            registry.RegisterCustomBindingFactory<UISegmentedControl> ("Title", segmentTitle => new MvxSegmentTitleTargetBinding (segmentTitle));
        }
    }
    

    And the following custom target binding.

    public class MvxSegmentTitleTargetBinding : MvxConvertingTargetBinding
    {
        public MvxSegmentTitleTargetBinding(object target) : base(target)
        {
    
        }
    
        public override Type TargetType
        {
            get {return typeof(MyViewModel);}
        }
    
        protected override void SetValueImpl(object target, object value)
        {
            var segmentControl = (UISegmentedControl)target;
            MyViewModel myViewModel = (MyViewModel)value;
    
            segmentControl.SetTitle(myViewModel.MyFirstValue, 0);
            segmentControl.SetTitle(myViewModel.MySecondValue, 1);
        }
    }
    

    And use it in your view like so.

    set.Bind (MySegmentControl).For ("Title").To ((MyViewModel vm) => vm);