我正在尝试在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元素失去焦点。
有没有办法附加一个事件,以便我们可以响应对入口元素值的不定键击更改?
答案 0 :(得分:2)
我不会使用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;
}
}