如何使用MVVMCross绑定到UISegmentedControl段的标题?

时间:2015-07-23 09:04:54

标签: ios xamarin mvvmcross

是否可以将视图模型的属性绑定到UISegmentedControl中的段标题?

我知道SetTitle()方法,但不确定它是否可以在MvvmCross中绑定到它。

1 个答案:

答案 0 :(得分:1)

Kiliman's answer建立在类似的问题上。

按照该答案的前两个步骤操作。然后创建以下自定义绑定构建器。

public class MyTouchBindingBuilder : MvxTouchBindingBuilder
{
    protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
    {
        base.FillTargetFactories (registry);

        registry.RegisterCustomBindingFactory<UISegmentedControl> ("Title", segmentTitle => new MvxSegmentTitleTargetBinding (segmentTitle));
    }
}

以下自定义目标绑定。

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);
    }
}

并在您的视图中使用它。

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