2

我正在尝试利用 Monotouch.Dialog 中的 EntryElement 的 CHANGED 事件,以便我可以获取任何输入字符串的长度,并在它达到一定长度后对其进行操作,例如

RootElement root = new RootElement (null);
Section pinSection = new Section ("", "Please enter your 6 digit pin");
EntryElement pin = new EntryElement("Enter your pin","","",false);
pin.KeyboardType = UIKeyboardType.NumberPad;

pin.Changed += (object sender, EventArgs e) => {
Console.WriteLine("Pin Changed to {0}, Length: 1}",pin.Value,pin.Value.ToString().Length);
                };

更新值时不会触发 CHANGED 事件。它仅在用户停止编辑并且 entry 元素失去焦点时触发。

有没有办法附加一个事件,以便我们可以响应对 entry 元素值的个别击键更改?

4

1 回答 1

3

我不使用 Changed 事件,而是将 EntryElement 子类化并覆盖 CreateTextMethod。我将其用作仅整数的 EntryElement,您应该能够通过添加您自己的事件来适应您的任务,该事件将在达到文本长度时被触发

public class IntegerEntryElement : EntryElement
{
    public IntegerEntryElement (string c, string p, string v) : base(c, p, v)
    {
        _maxLength = 0;
        TextAlignment = UITextAlignment.Right;
    }

    static NSString cellKey = new NSString("IntegerEntryElement");

    protected override NSString CellKey { get { return cellKey; } }
    private int _maxLength;
    public int MaxLength
    {
        get { return _maxLength; }
        set
        {
            if ((value >= 0) || (value <= 10))
            {
                _maxLength = value;
            }
        }
    }

    public int IntValue
    {
        get
        {
            int intValue = 0;
            Int32.TryParse(Value, out intValue);
            return intValue;
        }
        set
        {
            Value = value.ToString();
        }

    }

    public void Clear()
    {
        Value = "";
    }

    protected override UITextField CreateTextField (RectangleF frame)
    {
        RectangleF newframe = frame;
        newframe.Width -= 10;

        UITextField TextField = base.CreateTextField (newframe);

        TextField.KeyboardType = UIKeyboardType.NumberPad;
        TextField.ClearButtonMode = UITextFieldViewMode.WhileEditing;

        TextField.ShouldChangeCharacters = (UITextField textField, NSRange range, string replacementString) =>
        {
            bool result = true;
            string filter="0123456789";

            result = (filter.Contains(replacementString) || replacementString.Equals(string.Empty));

            if ((result) && (MaxLength > 0))
            {
                result = textField.Text.Length + replacementString.Length - range.Length <= MaxLength;
            }

            return result;
        };
        return TextField;
    }

}
于 2013-09-24T20:06:59.857 回答