行为 - 可绑定属性

时间:2016-08-18 16:34:24

标签: c# xamarin bindable

我已经创建了验证电子邮件输入的行为。在网上举了很多例子。如您所见,我的行为有两个可绑定属性,一个是IsValid,第二个是ErrorMessage。

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

BindableProperty“ErrorMessage”是readonly。

有没有人知道为什么会这样?提前谢谢!

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;
    }
}

2 个答案:

答案 0 :(得分: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); }
}`

答案 1 :(得分:-1)

更改此行

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

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