Ended事件UITextField上的MVVMCross绑定文本

时间:2014-04-02 16:43:00

标签: ios mvvmcross

我正在尝试在UITextField的子类上实现自定义绑定,以便在用户完成编辑而不是每次击键时设置绑定值,因为某些临时值在viewmodel中无效(例如,在设置时)年龄'到'26',值'2'无效,所以我想等待设置值,直到两个数字都存在)。类似于在xaml中设置UpdateSourceTrigger的东西。我在这里看了几个例子: MvvmCross UITextField custom bindingMvvmCross: change update source trigger property of binding on MonoDroid类似(但适用于Android)。我还看了N = 28自定义绑定并查看了MvxUITextFieldTextTargetBinding的源代码。

我认为我很接近,但我的自定义绑定永远不会被创建,并且我的应用程序中的UITextFields仍然会在每次按键时FireValueChanged。

我创建了以下自定义绑定:

public class UITextFieldFocusChangedBinding : MvxTargetBinding
{
    private bool _subscribed;
    private UITextField _view;
    public UITextFieldFocusChangedBinding(UITextField target) : base(target)
    {
        _view = target;
    }

    public override void SetValue(object value)
    {

        if (_view == null) return; 
        _view.Text = (string)value;
    }

    public override void SubscribeToEvents()
    {
        var view = _view;
        if (view == null)
            return;
        view.Ended += TextFieldOnEnded;
    }

    private void TextFieldOnEnded(object sender, EventArgs eventArgs)
    {
        var view = _view;
        if (view == null)
            return;
        if (!view.IsFirstResponder)
            FireValueChanged(view.Text);
        _subscribed = true;

    }
    public override Type TargetType
    {
        get { return typeof(string); }
    }

    public override MvxBindingMode DefaultMode
    {
        get { return MvxBindingMode.TwoWay; }
    }

    protected override void Dispose(bool isDisposing)
    {
        if (isDisposing)
        {
            var view = _view;
            if (view != null && _subscribed)
            {
                view.Ended -= TextFieldOnEnded;
                _subscribed = false;
            }
        }
        base.Dispose(isDisposing);
    }

}

我的setup.cs包含以下内容:

protected override void FillTargetFactories(IMvxTargetBindingFactoryRegistry registry)
{
    base.FillTargetFactories(registry);
    registry.RegisterPropertyInfoBindingFactory(typeof(Bindings.UITextFieldFocusChangedBinding),typeof(UITextField), "Text");
}

在我的MvxViewController中我有:

var set = this.CreateBindingSet<LifeNeedsView, LifeNeedsViewModel>();
set.Bind(_txtFinMedExpenses).To(vm => vm.FinalMedicalExpenses);
set.Apply();

绑定工作(值正确传递)但每次击键都有效。关于我可能缺少什么的任何建议?

0 个答案:

没有答案