自定义控件绑定不起作用

时间:2014-01-13 08:57:12

标签: c# ios mvvmcross

我为ios创建了一个自定义的numbpad控件,现在尝试将它与MVVMCross绑定到我的ViewModel。但它不起作用,ViewModel中的值始终为null。

NumberPad的代码是:

    [Register("NumberPad")]
public partial class NumberPad : UIView
{

    public string Text {
        get;
        set;
    }


    public NumberPad(IntPtr h): base(h)
    {
        //SetUp ();         
    }

    public NumberPad (RectangleF frame) : base(frame)
    {
        SetUp ();

    }

    public NumberPad ()
    {           
        //SetUp ();         
    }

    void SetUp ()
    {
        var arr = NSBundle.MainBundle.LoadNib ("NumberPad", this, null);
        var v = Runtime.GetNSObject (arr.ValueAt (0)) as UIView;
        v.Frame = new RectangleF (0, 0, Frame.Width, Frame.Height);
        AddSubview (v);

        Number0.TouchUpInside += HandleTouchUpInside;
        Number1.TouchUpInside += HandleTouchUpInside;
        Number2.TouchUpInside += HandleTouchUpInside;
        Number3.TouchUpInside += HandleTouchUpInside;
        Number4.TouchUpInside += HandleTouchUpInside;
        Number5.TouchUpInside += HandleTouchUpInside;
        Number6.TouchUpInside += HandleTouchUpInside;
        Number7.TouchUpInside += HandleTouchUpInside;
        Number8.TouchUpInside += HandleTouchUpInside;
        Number9.TouchUpInside += HandleTouchUpInside;

    }

    void HandleTouchUpInside (object sender, EventArgs e)
    {
        int tag = ((UIButton)sender).Tag;

        if (tag >= 0 && tag <= 9) {
            Text = String.Format("{0}{1}",Text,tag);
        } else if (tag == 10 && Text.Length > 0) {
            Text = Text + Text.Substring (0, Text.Length - 1);
        }
    }
}

和Binding这样:

set.Bind(numberPad).For(vm => vm.Text).To (vm => vm.Password);

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

如果您希望MvvmCross自动获取属性中的更改,请执行以下操作:

public string Text {
    get;
    set;
}

然后你必须给MvvmCross某种方式知道该属性已经改变了值。最简单的方法是简单地提供一个具有传统名称的事件,并在文本更改时提出此更改 - 例如:

public event EventHandler TextChanged;

private string _text;
public string Text {
    get { return _text; }
    set {  _text = value; TextChanged.Raise(this);  }
}

有关自定义控件和自定义绑定的更多信息,请参阅http://mvvmcross.blogspot.co.uk/中的N = 18,19,20和28