2

我创建了一个用于验证电子邮件输入的行为。跟随网络上的许多例子。如您所见,我的行为有两个可绑定属性,一个是 IsValid,第二个是 ErrorMessage。

在文本更改时,应用程序运行正则表达式验证,并且没有任何问题将值 true/false 分配给 IsValid 属性。但是当它试图为 ErrorMessage 属性赋值时,它会触发异常:

BindableProperty“ErrorMessage”是只读的。

有谁知道为什么会这样?提前致谢!

public class EmailValidatorBehavior : Behavior<Entry>
{
    const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
    @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";

    static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(EmailValidatorBehavior), false);

    public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;

    static readonly BindablePropertyKey ErrorMessagePropertyKey = BindableProperty.CreateReadOnly("ErrorMessage", typeof(String), typeof(EmailValidatorBehavior), "");

    public static BindableProperty ErrorMessageProperty = ErrorMessagePropertyKey.BindableProperty;


    public bool IsValid
    {
        get { return (bool)base.GetValue(IsValidProperty); }
        private set { base.SetValue(IsValidPropertyKey, value); }
    }

    public string ErrorMessage
    {
        get { return (string)base.GetValue(ErrorMessageProperty); }
        private set { base.SetValue(ErrorMessageProperty, value); }
    }


    void HandleTextChanged(object sender, TextChangedEventArgs e)
    {


        IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex,        
RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
        ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;

        if (String.IsNullOrEmpty(e.OldTextValue))
            ErrorMessage = "";
        else
        {
            ErrorMessage = "Please enter email address";
            return;
        }
        if (!IsValid)
            ErrorMessage = "Please enter valid email address";
        else
            ErrorMessage = "";

    }


    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += HandleTextChanged;
    }
    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= HandleTextChanged;
    }
}
4

2 回答 2

1

我认为这是因为你有private set,所以也许这将是一个解决方案:

`public bool IsValid
{
    get { return (bool)base.GetValue(IsValidProperty); }
    set { base.SetValue(IsValidPropertyKey, value); }
}

public string ErrorMessage
{
    get { return (string)base.GetValue(ErrorMessageProperty); }
    set { base.SetValue(ErrorMessageProperty, value); }
}`
于 2016-08-18T16:40:42.517 回答
-1

更改此行

private set { base.SetValue(ErrorMessageProperty, value); }

private set { base.SetValue(ErrorMessagePropertyKey, value); }
于 2017-08-14T09:11:26.833 回答